Tutorial Angular 6 PWA with Firebase Firestore

An interesting article to start creating PWA with Firebase in 5 mins

An interesting article to start creating PWA with Firebase in 5 mins

How to Use Algolia with Firebase Angular Apps

How to Use Algolia with Firebase Angular Apps

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it.

What is Algolia?

Algolia is a super powerful, scalable API service that allows developers to send different forms of data into their platform and quickly perform search, sort and complex filter queries on top of it. The service is incredibly fast, by using replica indexes to pre-build common query conditions to send your data back as quick as possible.

Why use Algolia with Firebase?

Firebase has come a long way in terms of its accessibility with querying data structures, especially in Firestore. Even with these advancements, it has limitations and often time requires pre-sorted data, using Firebase’s syntax sugar with push ids (push ids contain a date hash in their generation) and sacrificing extra reads/writes and straight forward object structure. Firebase also officially recommends Algolia for performing full-text search operations in Firestore.

Getting Started

In this working example, we will be using Firebase Cloud Functions with triggers to help assist with syncing data changes from Firestore over to Algolia. We will also be using the Algolia Node.JS and JavaScript client module for interacting with their service.

Firebase Cloud Functions

In your functions directory you will need to install the following dependencies to leverage Algolia.

npm install --save algoliasearch @types/algoliasearch

For this example we will listen for whenever a new user document is created, updated or deleted in our custom Firestore collection “users”.

For each of the below examples you will need to replace appId and apiKey with your own access tokens generated through Algolia’s admin panel.

user.onCreate.ts

The userOnCreate trigger is dispatched every time a new document is created in the users collection. In the example below we initialize Algolia with our app’s id and unique API key and initialize the index we want to use in Algolia. Algolia recommends naming your index by the instance/environment you are working with (i.e. dev_, prod_, staging_, next_).

We are also replicating to indexes so that we can sort by the user’s name in either ascending or descending order. Algolia reserves objectID for correlating records in their world; we will use the new document’s path id.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnCreate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
await index.setSettings({
replicas: [
'dev_users_name_desc',
'dev_users_name_asc'
]
});
return index.addObject({
objectID: change.id,
...user
});
});

user.onUpdate.ts

The userOnUpdate trigger is very similar to the create trigger. The difference is that we do not need to re-specify the replica indexes since once we register them; they will automatically push data over to the replica indexes any time we write to the parent index (dev_users).

To reduce the operation cost, Algolia allows partial updates to only change specific properties on an index’s object.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnUpdate = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const user = change.data();
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.partialUpdateObject({
objectID: change.id,
...user
});
});

user.onDelete.ts

The userOnDelete trigger is the simplest operation with an initialize and delete object call to remove the Algolia object by the objectID we defined earlier.

import * as algoliasearch from 'algoliasearch';
import * as functions from 'firebase-functions';

export const userOnDelete = functions.firestore
.document('users/{id}')
.onCreate(async (change, context) => {
const client = algoliasearch('appId', 'apiKey');
const index = client.initIndex('dev_users');
return index.deleteObject(change.id);
});

Export all of these constants to your root index.ts file. This will register them as new Firebase Cloud Functions when you build and deploy. At this point any time you change documents in Firestore (either directly through the Firebase Console or with your app) it will trigger these functions to push and sync data across to Algolia.

firebase deploy --only functions:userOnCreate,functions:userOnUpdate,functions:userOnDelete
Application Side
You can store Algolia’s search-only access token (this is different than the apiKey used in Cloud Functions) in your environments file to easily access/import it.

Create a simple service to easily interact with your Algolia indexes.

user.service.ts

import * as algoliasearch from 'algoliasearch';

@Injectable()
export class UserService {

client: algoliasearch.Client;

init(config: {
appId: string,
apiKey: string
}) {
this.client = algoliasearch('appId', 'apiKey');
}

fetchUsers(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users');
return userSearch.search(options);
}

fetchUsersByNameAsc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_asc');
return userSearch.search(options);
}

fetchUsersByNameDesc(options: algoliasearch.QueryParameters) {
const userSearch = this.client.initIndex('dev_users_name_desc');
return userSearch.search(options);
}

}

In your component, provide UserService and make the following method calls to test the response back from Algolia.

async ngOnInit() {
this.init({ appId: 'foo', apiKey: 'bar' });
const res = await this.fetchUsers({
page: 0,
length: 10,
query: 'Sean'
});
console.log('res', res);
}

This method call will attempt to load the first page of results, up to 10 records that has a searchable attribute that matches “Sean”.

Final Thoughts

Without getting too far into the weeds of Algolia’s client and explicitly focusing on syncing data over and quickly logging that information out; we can see that Algolia serves as a powerful interface to receive the exact data we need.

In our implementation on Hive, we use Algolia to handle paginated admin tables, infinite scroll experiences, pre-filtering collection records by specific conditions and sorting table data. You can also leverage Algolia as a read-only database, only storing/syncing documents that the client should have access to. This is powerful when using concepts such as soft deletes, where you stamp a document with a deletedAt timestamp in Firestore and remove the object from Algolia. By doing this, you can always recover the document back, but all querying logic from Algolia will treat the document as being deleted.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Further reading

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers


Originally published on medium.com

How to Build Progressive Web Apps (PWA) using Angular 9

How to Build Progressive Web Apps (PWA) using Angular 9

In this Angular 9 PWA tutorial, we will use the most recent version of Angular 9 to build a Progressive Web Application (PWA) that works on mobile or any platform that uses a standard-compliant browser. Creating Progressive Web Apps Using Angular 9. How to convert the existing angular application to PWA? How to Add PWA features in an angular application? How to work with Service Workers? How to configure the add-to-home-screen feature using web manifest file? How to audit the PWA app with Google’s Lighthouse extension?

In this tutorial, we will use the most recent version of Angular 9 to build a Progressive Web Application (PWA) that works on mobile or any platform that uses a standard-compliant browser.

What is PWA?

A progressive web app offers the high level of user experience because it has the same features as native apps have. Nowadays, PWA has become the big deal, and more companies are switching towards the Progressive web applications (PWA).

PWA does not require to be deployed via app stores; instead, we take a slightly different approach and deploy it through the web servers through URLs. To make the same PWA as the native apps, we have to fulfill the following requirements.

Responsive

Runs on almost every device desktop, mobile, or tablet.

Auto-Updated

Service worker keeps it always updated.

Secure

Content is considered to be safe due to serving through HTTPS.

Reliably Connected

Service workers support to make it work offline and on sparse networks.

Progressive

Web app that employs modern web capabilities to produce an app-like experience for every user.

Searchable

Very much searchable via search engines due to web app manifest.

Shareable

It does not require to be downloaded can easily be shared via a simple link or URL.

User Experience

Similar user experience by engaging the same interaction methodology as a native app has.

Installable

Fully installable on users’ mobile home screen, and the good thing is we do not have to visit the app store.

Regularly Communicate

Keeps you up to date via push notifications and offers you the latest updates, promotion offers, etc.

Table of Contents:

  • Configuring & Installing Angular Application
  • Adding Angular Material Library
  • Build & Consume REST API using HttpClient
  • Adding PWA in Angular 8/9
  • Service Workers in Angular
  • Configure Production Build with http-server
  • Audit PWA App with Lighthouse
  • Conclusion
Configuring & Installing Angular Application

In this step, we will configure the Angular project for giving you the demo of Angular PWA.

First, you make sure that you have the latest version of Node.js and NPM configured on your system.

node -v

# v10.16.0

Follow this URL to download and install Node & NPM.

Now, we are going to begin with installing the latest version of Angular CLI on your system.

npm install -g @angular/[email protected]

Run the following command to install an Angular app:

ng new angular-pwa

Get inside the project directory:

cd angular-pwa
Adding Angular Material Design UI Library

Adding a Material design library in Angular is very easy, It can be done by using just a single command. Run the following command from your terminal.

ng add @angular/material

Add the material theme in src/styles.css file.

@import "[email protected]/material/prebuilt-themes/indigo-pink.css";

Ordinarily, we import the angular material components in the AppModule. But there is a slight twist. We are going to create a separate module file for material components and import the components here and then import the material component file inside the main AppModule file.

This is the process I highly recommend for managing the material components in an organized way. We will show the users data into the angular material table, Create app/material.module.ts file add the following code inside of it.

import { NgModule } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, MatToolbarModule } from '@angular/material';

@NgModule({
    imports: [
        MatTableModule,
        MatPaginatorModule,
        MatToolbarModule
    ],
    exports: [
        MatTableModule,
        MatPaginatorModule,
        MatToolbarModule
    ]
})

export class MaterialModule { }

Next, import MaterialModule module in the main app.module.ts file as given below.

import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

/* angular material */
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

export class AppModule { }
Build & Consume REST API using HttpClient

In this step, create angular service to fetch the data from the remote server using an open-source REST API.

To make the HTTP requests we need to import and register HttpClientModule service in app.module.ts file.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
   ]
})

Let’s generate a service. In here, we will write the logic to fetch the users’ data with the help of JSONPlaceholder API, run the following command.

ng g service rest-api

Next, open the app/rest-api.service.ts file and add the following code in it:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export interface User {
  id: string;
  name: string;
  email: string;
  website: string;
}

@Injectable({
  providedIn: 'root'
})

export class RestApiService {
  api: string = "https://jsonplaceholder.typicode.com/users";

  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.api)
  }
}

We are fetching the User data using the HttpClient service as an Observable via getUsers() method.

Next, open the app/app.component.ts file and add the given below code:

import { Component, ViewChild } from '@angular/core';
import { RestApiService } from './rest-api.service';
import { MatPaginator, MatTableDataSource } from '@angular/material';

export interface TableElement {
  id: string;
  name: string;
  email: string;
  website: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  Data: TableElement[];
  col: string[] = ['id', 'name', 'email', 'website'];
  dataSource = new MatTableDataSource<TableElement>(this.Data);
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(private restApiService: RestApiService) {
    this.restApiService.getUsers().subscribe((res) => {
      this.dataSource = new MatTableDataSource<TableElement>(res);
      setTimeout(() => {
        this.dataSource.paginator = this.paginator;
      }, 0);
    })
  }

}

We imported the RestApiService in AppComponent to fetch and display the user data. We are using Angular Material table UI component to display the data. We can manipulate the item’s size using the angular material pagination module.

Build the PWA app UI using the angular material table, go to the app.component.html file to create the layout. Our layout will have the material navbar and a data table with pagination.

<mat-toolbar color="accent" class="header">
  <span>Angular PWA Example</span>
</mat-toolbar>

<table mat-table [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> ID. </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <ng-container matColumnDef="email">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Email </th>
    <td mat-cell *matCellDef="let element"> {{element.email}} </td>
  </ng-container>

  <ng-container matColumnDef="website">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Website </th>
    <td mat-cell *matCellDef="let element"> {{element.website}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="col"></tr>
  <tr mat-row *matRowDef="let row; columns: col;"></tr>
</table>

<mat-paginator [pageSizeOptions]="[7, 14, 28]" showFirstLastButtons></mat-paginator>

Adding PWA in Angular 8/9

It is undoubtedly very easy to convert an existing angular application into a Progressive Web App (PWA). The “ng add angular pwa” command can make your dreams come true.

ng add @angular/pwa

The above command automatically add PWA files and features inside an Angular app:

  • The manifest.webmanifest file
  • The ngsw-config.json service worker
  • Varying sizes of icons inside the assets/icons directory

The “index.html” file has been updated and added the following meta tag and theme colour attribute.

  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">

Please make sure and add few PWA compliant icon assets.

Service Workers in Angular

A Service Worker is a script that works in the background and gets along with almost every modern browsers.

Service Workers work with HTTPS and works in the same manner as Web Workers does but a bit adversely. Progressive Web Application considers service workers as the primary technology. It allows deep platform integration, such as offline support, background sync, rich caching, and push notifications.

The “ng add angular pwa” command generated the ngsw-config.json file, It is solely responsible for service workers. Service workers are also automatically added to app.module.ts file.

// app.module.ts

import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [...],
  imports: [
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [...]
})

export class AppModule { }

Have a look at the ngsw-config.json file.

// ngsw-config.json

{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/manifest.webmanifest",
          "/*.css",
          "/*.js"
        ]
      }
    }, {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}

The “ng add angular pwa” command also registered the service-worker inside the package.json file:

// package.json

{
  "dependencies": {
    ...
    "@angular/service-worker": "~8.2.14"
    ...
  }
}

The feature will only work with the app, which is being served with HTTPS.

Configure Production Build with http-server

Install the http-server package globally via NPM using the following command.

sudo npm install -g http-server

The http-server is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it’s simple and hackable enough to be used for testing, local development, and learning.
http-server

Run ng build prod command to build the app for production environment.

ng build --prod

Now, we have the production build ready at the dist/angular-pwa folder. Next, we will serve the angular PWA using the http-server package.

Get inside the prod build folder.

cd dist/angular-pwa

Start the prod build
Next, run the following command in your terminal.

http-server -o

The above command will open the angular app on the following URL http://127.0.0.1:8080 and also give you the following URLs, you can check your app by entering one of the URL in the browser’s address bar.

Available on:
http://127.0.0.1:8080
http://192.168.0.102:8080

Audit PWA App with Lighthouse

Now, we will verify the PWA application using Lighthouse extension on the Google Chrome browser. Add the following URL on the browser’s address bar: http://127.0.0.1:8080

Install the lighthouse extension from chrome web store.

Next, open the browser console by using the Ctrl + Shift + I.

Conclusion

Finally, we have completed the Angular 9 PWA tutorial with an example. In this tutorial, we have got a chance to do the cover the following topics:

  • How to convert the existing angular application to PWA?
  • How to Add PWA features in an angular application?
  • How to work with Service Workers?
  • How to configure the add-to-home-screen feature using web manifest file?
  • How to audit the PWA app with Google’s Lighthouse extension?

Download the full code of this tutorial from this GitHub repository, I hope you will like this tutorial. Happy Coding!

Building Angular 9 Authentication System from scratch using Firebase

Building Angular 9 Authentication System from scratch using Firebase

In this Angular 9 Firebase Authentication tutorial, we are going to build full Angular 9 Firebase Authentication system from scratch using Firebase Real-time NoSQL cloud database.

In this Angular tutorial, we are going to build full Angular 9 Firebase Authentication system from scratch using Firebase Real-time NoSQL cloud database.

What We’ll Be Creating?
  • Sign in with Google
  • Sign in with username/password
  • Sign up with username/password
  • Recover forget password
  • Send email verification to a newly created user
  • Protect app’s inner pages URL using route guard’s canActivate method
  • Prevent user to access sign in and sign up URL when a user is already logged in
  • Maintain logged in state of Firebase user in localStorage

Step by step Explanation

  • Technologies used
  • Prerequisite
  • Firebase account set up and AngularFire2 library integration
  • Generate required Angular components
  • Setup router service for navigating between components
  • Create firebase authentication service using Firebase API
  • Create Sign in authentication service using AuthService API
  • Create sign in with Username/Password
  • Create sign in with Google
  • Create sign in with Facebook
  1. Create Firebase sign up service using Firebase API in Angular 7|8|9
  2. Create Firebase forgot password service using Firebase API in Angular 7|8|9
  3. How to send email Verification using Firebase API in Angular 7|8|9?
  4. How to use CanActivate method to prevent Access of URLs in Angular 7 app using route guards?
  5. How to maintain logged in state of Firebase user in localStorage with Angular 7|8|9?
1. Technologies used
  • Node 8.11.1
  • Angular 7|8|9
  • Firebase 5.7.0
  • RxJS 6.3.3
  • Typescript 3.1.6
2. Prerequisite

– Setup Node JS development environment

Before we move ahead I’m assuming you already have Node JS development environment set up in your system.

Please follow this link How to Set up Node JS Development Environment?

– Install Angular CLI

Install Angular CLI, Ignore if Angular CLI is already installed.

npm install -g @angular/cli

– Angular 7|8|9 Project Set up

Use the given below cmd to setup the Angular project.

ng new angularfiebase-authentication

Once the project is downloaded, get into the project directory.

cd angularfirebase-authentication

Congrats! You are in your project directory.

For the demo purpose, we’ll be using Bootstrap4, use the given below command to install Bootstrap4 in your project.

npm install bootstrap

Go to angular.json file and replace the given below code with “styles”: [ ] array.

"styles": [
            "node_modules/bootstrap/dist/css/bootstrap.min.css",
            "src/styles.css"
          ]

Run the following command to start your project.

ng serve --open
3. Firebase Account Set up and AngularFire2 Library Integration

I assume you have already created a basic project in Firebase account

How to include Firebase AngularFire2 library in your Angular app?

Include AngularFire2 library in your Angular 7|8|9 app from Node Package Manager(NPM).

Run the given below command using Angular CLI.

npm install firebase @angular/fire --save

Once the AngularFire2 library included in the app then go to src/app/app.module.ts file and add the given below code.

// Firebase services + enviorment module
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFirestoreModule,
  ]
})
4. Generate Required Angular Components

In order to create a complete Angular 7|8|9 Firebase Authentication system, we are required to generate components, services, route guards, routing services etc.

Generate Components for Angular Firebase Authentication System App

ng g c components/dashboard
ng g c components/sign-in
ng g c components/sign-up
ng g c components/forgot-password
ng g c components/verify-email

5. Setup Router Service for Navigating between Components

Create Angular router service for navigating between components in Auth app. When we initially create a new project using Angular CLI. Angular CLI asks to create routing service where you have to simply choose yes and hit enter.

Digambers-MacBook-Pro:Desktop digambersingh$ ng new angularfirebase-authentication
? Would you like to add Angular routing? (y/N)

This will create src/app-routing.module.ts file. In our project, we have kept this file in the src/shared/routing/app-routing.module.ts folder for the better manageability purpose.

Go to src/shared/routing/app-routing.module.ts file, paste the given below code for creating navigation service in your Angular Firebase authentication system app.

import { NgModule } from '@angular/core';
// Required services for navigation
import { Routes, RouterModule } from '@angular/router';

// Import all the components for which navigation service has to be activated 
import { SignInComponent } from '../../components/sign-in/sign-in.component';
import { SignUpComponent } from '../../components/sign-up/sign-up.component';
import { DashboardComponent } from '../../components/dashboard/dashboard.component';
import { ForgotPasswordComponent } from '../../components/forgot-password/forgot-password.component';
import { AuthGuard } from "../../shared/guard/auth.guard";
import { VerifyEmailComponent } from '../../components/verify-email/verify-email.component';

const routes: Routes = [
  { path: '', redirectTo: '/sign-in', pathMatch: 'full' },
  { path: 'sign-in', component: SignInComponent },
  { path: 'register-user', component: SignUpComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'forgot-password', component: ForgotPasswordComponent },
  { path: 'verify-email-address', component: VerifyEmailComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Go to app.module.ts file and include app routing service and also include in imports array like given below.

// App routing modules
import { AppRoutingModule } from './shared/routing/app-routing.module';

@NgModule({
  declarations: [...],
  imports: [
    AppRoutingModule
  ],
  providers: [...],
  bootstrap: [...]
})
6. Create Firebase Authentication Service using Firebase API

Generate auth service and user interface files to create a Firebase authentication system with Angular 7|8|9.

– Create user.ts file

ng generate interface shared/services/user

Go to shared/services/user.ts
This user interface class will hold the data types of the User class.

export interface User {
   uid: string;
   email: string;
   displayName: string;
   photoURL: string;
   emailVerified: boolean;
}

– Create auth.service.ts file

This file holds the core logic of our authentication system. I’ll be covering up social login using Firebase’s Google auth provider. You can also create the login with Facebook, Twitter, and GitHub later on by following the same method.

I am also going to cover up the sign in and sign up using username/password, reset forgot password, email verification, route protection using canActivate auth guard method.

import { Injectable, NgZone } from '@angular/core';
import { User } from "../services/user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,  
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {    
    /* Saving user data in localstorage when 
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Sign up with email/password
  SignUp(email, password) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        /* Call the SendVerificaitonMail() function when new user sign 
        up and returns promise */
        this.SendVerificationMail();
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Send email verfificaiton when new user sign up
  SendVerificationMail() {
    return this.afAuth.auth.currentUser.sendEmailVerification()
    .then(() => {
      this.router.navigate(['verify-email-address']);
    })
  }

  // Reset Forggot password
  ForgotPassword(passwordResetEmail) {
    return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
    .then(() => {
      window.alert('Password reset email sent, check your inbox.');
    }).catch((error) => {
      window.alert(error)
    })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  // Sign in with Google
  GoogleAuth() {
    return this.AuthLogin(new auth.GoogleAuthProvider());
  }

  // Auth logic to run auth providers
  AuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
    .then((result) => {
       this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        })
      this.SetUserData(result.user);
    }).catch((error) => {
      window.alert(error)
    })
  }

  /* Setting up user data when sign in with username/password, 
  sign up with username/password and sign in with social auth  
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
    const userData: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      emailVerified: user.emailVerified
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out 
  SignOut() {
    return this.afAuth.auth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['sign-in']);
    })
  }

}

After that, go to src/app.module.ts file and import authentication service and pass the AuthService class into providers: [AuthService] array. By doing this our authentication service will be available throughout the application.

// Auth service
import { AuthService } from "./shared/services/auth.service";

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [AuthService],
  bootstrap: [...]
})
7. Create Sign in Authentication Service using AuthService API

It’s time to consume custom AuthService API, we’ll be consuming following services using AuthService API.

  • Create Sign in with Username and Password
  • Create Sign in with Google
  • Create Sign in with Facebook

In order to consume custom API from AuthService class we need to import AuthService class into src/app/components/sign-in/sign-in.component.ts file and then inject AuthService class into the constructor so that these services will be available throughout the same template.

Go to src/app/components/sign-in/sign-in.component.ts file and paste the following code.

import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.css']
})

export class SignInComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() { }

}

We’ve already generated our components, go to src/app/components/sign-in/sign-in.component.html file and paste the following code.

<div class="displayTable">
  <div class="displayTableCell">

    <div class="authBlock">
      <h3>Sign In</h3>
      <div class="formGroup">
        <input type="text" class="formControl" placeholder="Username" #userName required>
      </div>

      <div class="formGroup">
        <input type="password" class="formControl" placeholder="Password" #userPassword required>
      </div>

      <!-- Calling SignIn Api from AuthService -->
      <div class="formGroup">
        <input type="button" class="btn btnPrimary" value="Log in" (click)="authService.SignIn(userName.value, userPassword.value)">
      </div>

      <div class="formGroup">
        <span class="or"><span class="orInner">Or</span></span>
      </div>

      <!-- Calling GoogleAuth Api from AuthService -->
      <div class="formGroup">
        <button type="button" class="btn googleBtn" (click)="authService.GoogleAuth()">
          <i class="fab fa-google-plus-g"></i>
          Log in with Google
        </button>
      </div>

      <div class="forgotPassword">
        <span routerLink="/forgot-password">Forgot Password?</span>
      </div>
    </div>

    <div class="redirectToLogin">
      <span>Don't have an account?<span class="redirect" routerLink="/register-user"> Sign Up</span></span>
    </div>

  </div>
</div>

8. How to Create Firebase Sign up Service using Firebase API in Angular 7|8|9?

In this section, I am going to share with you, how to create Firebase sign up service using Firebase API in Angular 7|8|9?

Go to src/app/components/sign-up/sign-up.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up.component.html',
  styleUrls: ['./sign-up.component.css']
})

export class SignUpComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() { }

}

Go to src/app/components/sign-up/sign-up.component.html file and add the following code.

<div class="displayTable">
  <div class="displayTableCell">

    <div class="authBlock">
      <h3>Sign Up</h3>

      <div class="formGroup">
        <input type="email" class="formControl" placeholder="Email Address" #userEmail required>
      </div>

      <div class="formGroup">
        <input type="password" class="formControl" placeholder="Password" #userPwd required>
      </div>

      <div class="formGroup">
        <input type="button" class="btn btnPrimary" value="Sign Up" (click)="authService.SignUp(userEmail.value, userPwd.value)">
      </div>

      <div class="formGroup">
        <span class="or"><span class="orInner">Or</span></span>
      </div>

      <!-- Continue with Google -->
      <div class="formGroup">
        <button type="button" class="btn googleBtn" (click)="authService.GoogleAuth()">
          <i class="fab fa-google-plus-g"></i>
          Continue with Google
        </button>
      </div>

      <!-- Continue with Facebook -->
      <div class="formGroup">
        <button type="button" class="btn facebookBtn" (click)="authService.FacebookAuth()">
          <i class="fab fa-facebook"></i>
          Continue with Facebook
        </button>
      </div>
    </div>

    <div class="redirectToLogin">
      <span>Already have an account? <span class="redirect" routerLink="/sign-in">Log In</span></span>
    </div>
  </div>

</div>
9. How to Create Firebase Forgot Password Service using Firebase API in Angular 7|8|9?

We are going to create Firebase forgot password service using Firebase API in Angular 7|8|9 using our custom made AuthService API.

Go to src/app/components/forgot-password/forgot-password.component.ts add the following code.

import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.css']
})

export class ForgotPasswordComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() {
  }

}

Go to src/app/components/forgot-password/forgot-password.component.html add the following code.

<div class="displayTable">
  <div class="displayTableCell">
    <div class="authBlock">
      <h3>Reset Password</h3>

      <p class="text-center">Please enter your email address to request a password reset.</p>

      <div class="formGroup">
        <input type="email" class="formControl" placeholder="Email Address" #passwordResetEmail required>
      </div>

      <!-- Calling ForgotPassword from AuthService Api -->
      <div class="formGroup">
        <input type="submit" class="btn btnPrimary" value="Reset Password" (click)="authService.ForgotPassword(passwordResetEmail.value)">
      </div>
    </div>

    <div class="redirectToLogin">
      <span>Go back to ? <span class="redirect" routerLink="/sign-in">Log In</span></span>
    </div>

  </div>
</div>
10. How to Send Email Verification using Firebase API in Angular 7|8|9?

Firebase allows us to send email verification smoothly. I am going to show you how you can achieve this functionality easily using Firebase API.

Go to src/app/components/verify-email/verify-email.component.ts file and add the given below code.

import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";

@Component({
  selector: 'app-verify-email',
  templateUrl: './verify-email.component.html',
  styleUrls: ['./verify-email.component.css']
})
export class VerifyEmailComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() {
  }

}

Go to src/app/components/verify-email/verify-email.component.html file and add the given below code.

<div class="displayTable">
  <div class="displayTableCell">

    <div class="authBlock">
      <h3>Thank You for Registering</h3>

      <div class="formGroup" *ngIf="authService.userData as user">
        <p class="text-center">We have sent a confirmation email to <strong>{{user.email}}</strong>.</p>
        <p class="text-center">Please check your email and click on the link to verfiy your email address.</p>
      </div>

      <!-- Calling SendVerificationMail() method using authService Api -->
      <div class="formGroup">
        <button type="button" class="btn btnPrimary" (click)="authService.SendVerificationMail()">
          <i class="fas fa-redo-alt"></i>
          Resend Verification Email
        </button>
      </div>

    </div>

    <div class="redirectToLogin">
      <span>Go back to?<span class="redirect" routerLink="/sign-in"> Sign in</span></span>
    </div>

  </div>
</div>
11. How to Use CanActivate method to Prevent Access of URL in Angular 7|8|9 App using Route Guards?

In this section, I will be showing you how you can secure your app’s routes from unauthorized access using canActivate() route guard method. This method is pretty helpful when we need to secure our app’s URL.

First, go to src/app/shared/services/auth.service.ts file and look for the isLoggedIn() method. This function returns the boolean result to true when the user is logged in && user’s email is verified. If either condition doesn’t match it will return false and doesn’t allow users to access the desired pages.

import { AngularFireAuth } from "@angular/fire/auth";

export class AuthService {
  userData: any; // Save logged in user data

  constructor(
    public afAuth: AngularFireAuth, // Inject Firebase auth service
  ) {    
    /* Saving user data in localstorage when 
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

}

We have to secure all the inner pages in the app which are only accessible to logged in users.

To get this functionality, we have to generate route guard files. Run the below command to create route guards.

ng generate guard shared/guard/auth

Go to src/app/shared/guard/auth.guard.ts file and include the following code.

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../../shared/services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['sign-in'])
    }
    return true;
  }

}

We have successfully secured our app’s inner pages now if no user will be able to access our app’s inner pages unless they are logged in. If anybody puts the inner page’s URL in the browser directly then they will be redirected to the sign-in page.

Let’s create another guard which will prevent access for sign in, sign up, password recovery and email verification pages when the user is already logged in.

Run the below command to generate route guard.

ng generate guard shared/guard/secure-inner-pages.guard.ts

Go to src/app/shared/guard/secure-inner-pages.guard.ts file and include the following code.

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../../shared/services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class SecureInnerPagesGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn) {
      window.alert("You are not allowed to access this URL!");
       this.router.navigate(['dashboard'])
    }
    return true;
  }

}

We’ve successfully created canActivated guards now we have to include these guards in routes services.

Go to src/app/shared/routing/app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// Required components for which route services to be activated
import { SignInComponent } from '../../components/sign-in/sign-in.component';
import { SignUpComponent } from '../../components/sign-up/sign-up.component';
import { DashboardComponent } from '../../components/dashboard/dashboard.component';
import { ForgotPasswordComponent } from '../../components/forgot-password/forgot-password.component';
import { VerifyEmailComponent } from '../../components/verify-email/verify-email.component';

// Import canActivate guard services
import { AuthGuard } from "../../shared/guard/auth.guard";
import { SecureInnerPagesGuard } from "../../shared/guard/secure-inner-pages.guard";

// Include route guard in routes array
const routes: Routes = [
  { path: '', redirectTo: '/sign-in', pathMatch: 'full'},
  { path: 'sign-in', component: SignInComponent, canActivate: [SecureInnerPagesGuard]},
  { path: 'register-user', component: SignUpComponent, canActivate: [SecureInnerPagesGuard]},
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'forgot-password', component: ForgotPasswordComponent, canActivate: [SecureInnerPagesGuard] },
  { path: 'verify-email-address', component: VerifyEmailComponent, canActivate: [SecureInnerPagesGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }
12. How to Maintain Logged in State of Firebase User in localStorage with Angular 7|8|9?

I will be discussing with you how you can maintain the logged in user data in Local Storage with Angular.

Our logic is pretty straightforward when the user is logged in we will save the user data in Local Storage, user details will be available even if we refresh the page. We will remove the user data from local storage if we log out from the app.

Without wasting time let’s write our logic.

Go to src/app/services/auth.service.ts file and add the given below code.

import { Injectable, NgZone } from '@angular/core';
import { User } from "../services/user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,  
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {    
    /* Saving user data in localstorage when 
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Sign up with email/password
  SignUp(email, password) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        /* Call the SendVerificaitonMail() function when new user sign 
        up and returns promise */
        this.SendVerificationMail();
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Sign in with Google
  GoogleAuth() {
    return this.AuthLogin(new auth.GoogleAuthProvider());
  }  

  // Auth logic to run auth providers
  AuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
    .then((result) => {
       this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        })
      this.SetUserData(result.user);
    }).catch((error) => {
      window.alert(error)
    })
  }

  /* Setting up user data when sign in with username/password, 
  sign up with username/password and sign in with social auth  
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
    const userData: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      emailVerified: user.emailVerified
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out 
  SignOut() {
    return this.afAuth.auth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['sign-in']);
    })
  }

}

Consume AuthService API just go to src/app/components/dashboard/dashboard.component.html file and add the following code.

<!-- Top navigation -->
<nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
  <a class="navbar-brand col-sm-3 col-md-2 mr-0" routerLink="/register-student">
    <img class="brand-logo" src="assets/logo-positronx-white.svg" alt="positronX.io Logo">
    <span class="dasboard-text">Dashboard</span>
  </a>
</nav>

<!-- Sidebar navigation -->
<div class="container-fluid">
  <div class="row">

    <nav class="col-md-2 d-md-block bg-light sidebar">
      <div class="sidebar-sticky">
        <ul class="nav flex-column">
          <li class="nav-item">
            <a class="nav-link active">
              <i class="fas fa-user"></i>User Profile
            </a>
          </li>
          <!-- Calling SignOut() Api from AuthService -->
          <li class="nav-item">
            <a class="nav-link" (click)="authService.SignOut()">
              <i class="fas fa-sign-out-alt"></i>Log out
            </a>
          </li>
        </ul>
      </div>
    </nav>

    <!-- Main content -->
    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
      <div class="inner-adjust">

        <div class="pt-3 pb-2 mb-3 border-bottom">
          <h1 class="h2">User Profile</h1>
        </div>
        <!-- Show user data when logged in -->
        <div class="row" *ngIf="authService.userData as user">
          <div class="col-md-12">
            <div class="media">
              <img class="align-self-start mr-5 img-thumbnail rounded-circle" src="{{(user.photoURL) ? user.photoURL : '/assets/dummy-user.png'}}"
                alt="{{user.displayName}}">
              <div class="media-body">
                <h1>Hello: <strong>{{(user.displayName) ? user.displayName : 'User'}}</strong></h1>
                <p>User ID: <strong>{{user.uid}}</strong></p>
                <p>Email: <strong>{{user.email}}</strong></p>
                <p>Email Verified: <strong>{{user.emailVerified}}</strong></p>
              </div>
            </div>
          </div>
        </div>

      </div>
    </main>

  </div>
</div>

It will look like this.

Thank a lot for taking time to read this tutorial, I believe this tutorial has been helpful to you. If you think this tutorial has been helpful then please consider putting a star on my Git repo.