Angular 14 Tutorial- Firebase Send Email Example Tutorial

Angular 14 Firebase Send Email Example; In this Angular tutorial, we will see how to send verification emails to a new user. We will also learn how to prevent new users from accessing their accounts unless they validate their email addresses.

This Angular tutorial is compatible with version 4+ including latest version 12, 11, 10, 9, 8 ,7, 6 & 5.

Firebase offers many unique features for creating an authentication system. Sending email verification is not at all difficult with the Angular firebase.

We will be using this functionality in this Firebase tutorial using firebase API (AngularFire2 Library).

 

We will be using Angularfire2 Library from the Node Package manager (NPM) and the latest Angular release for this tutorial.

Here, we have to install the Firebase Packages in the Angular App:

npm install firebase @angular/fire

Now, we will add Firebase configuration in the environment.ts files:

export const environment = {
  production: false,
  firebase: {
    apiKey: "xxxxxxxx-xxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxx",
    appId: "xxxxx",
    measurementId: "xxxxxxxxxxxxxxxx"
  }
};

 

Create Auth Service

Further, we will execute the command to generate a service class file using the below command:

ng generate service auth

 

Remove TypeScript Errors

In order to remove strict type warnings or errors, we have to make sure to set “strict”: false , “noImplicitReturns”: false and “strictTemplates”: false under compilerOptions and angularCompilerOptions properties in tsconfig.json file.

 

Import AuthService Class in App.module.ts

// Auth service
import { AuthService } from "./shared/services/auth.service";
 providers: [
    AuthService
  ]

 

Create The Auth Service For Sending Verification Email Using Firebase auth.service.ts

import { Injectable, NgZone } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Router } from '@angular/router';
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router, // Inject Route Service
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {}
  // Send email verification when new user sign up
  SendVerificationMail() {
    return this.afAuth.currentUser
      .then((user) => {
        return user.sendEmailVerification();
      })
      .then(() => {
        this.router.navigate(['verify-email-address']);
      });
  }
  // Sign up with email/password
  SignUp(email, password) {
    return this.afAuth
      .createUserWithEmailAndPassword(email, password)
      .then((result) => {
        this.SendVerificationMail(); // Sending email verification notification, when new user registers
      })
      .catch((error) => {
        window.alert(error.message);
      });
  }
  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth
      .signInWithEmailAndPassword(email, password)
      .then((result) => {
        if (result.user.emailVerified !== true) {
          this.SendVerificationMail();
          window.alert(
            'Please validate your email address. Kindly check your inbox.'
          );
        } else {
          this.ngZone.run(() => {
            this.router.navigate(['<!-- enter your route name here -->']);
          });
        }
      })
      .catch((error) => {
        window.alert(error.message);
      });
  }
}

 

So, we have successfully created the auth.service.ts file and wrote straightforward logic in it. There are three methods in our AuthService Class:

  • SendVerificationMail(): This method sends a verification email to the newly created users using Firebase API with Angular.
  • SignUp(email, password): This method allows the users to create a new account and sends a verification email to a newly created user.
  • SignIn(email, password): This method prevents the user to access if the email address is not verified.

 

Conclusion

So friends, in this Angular 14 tutorial, we have learned how to send a verification email to the newly created users using Firebase API with Angular by now.

Hope that this tutorial will surely prove a great help.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *