You are currently viewing How to display loader on every HTTP request in Angular 8.

How to display loader on every HTTP request in Angular 8.

In general, it’s an essential requirement of any application that whenever any CRUD operation performs by the client on the server, the user should display a loader on the screen until get back a response from the server so that user should aware of some action are going on the server-side. In angular 8 this can be easily achievable using Interceptor, subject, and ngx-loading module.

In this article, we will see how to create and integrate the loader component step by step in an easy manner. Let us now see the steps

Install ngx-loading:  To install ngx-loading from npm in your project.

npm install --save ngx-loading	

Import the NgxLoadingModule in your root application module i.e. app-module

import { ReactiveFormsModule } from '@angular/forms';
import { LoaderComponent } from './loader/loader.component'
import { NgxLoadingModule } from 'ngx-loading';
 
@NgModule({
  declarations: [ 
    LoaderComponent
  ],
  imports: [    
NgxLoadingModule.forRoot({})
    
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create a new component with name loader using angular-cli command.

ng g c loader

This will create a component and updated the app-module (root-module).

import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.css']
})
export class LoaderComponent implements OnInit {
 
  constructor() { }
 
  ngOnInit() {
  }
 
}

Integrate with ngx-loading component in loader component.html

<div *ngIf="isLoading | async" class="overlay">
    <ngx-Loading [show]="isLoading"></ngx-Loading>    
</div>

We will write a service which is used to emit true/false value to the components who injecting the service.   

Create a service with name loader using angular-cli command.

ng g s loader

And here is the logic of loader-service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
 
@Injectable()
export class LoaderService {
    isLoading = new Subject<boolean>(); 
 
    display() {
        this.isLoading.next(true);
    }
 
    hide() {
        this.isLoading.next(false);
    }

Note: Here the subject is work like an Observable.

Now we will write an interceptor: Interceptors can be used in two different phases in a life cycle of an HTTP request to a server. i.e. before call made to the server and after getting the response from the server. Interceptor is a commonplace where you can check for all the request made to server from your application and check all the responses from the server.

Create an interceptor class with name loader-interceptor using the angular-cli command .

ng g class loader-interceptor
  • We need to Import the HttpEvent, HttpHandler, HttpInterceptor, HttpRequest into the interceptor.
  •  We need to add a class decorated with Injector Decorator, where we will write our logic for Interceptors.
  • Inject the loader-service into interceptor constructor for accessing the service logic.
import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";
import { finalize } from "rxjs/operators";
import { LoaderService } from '../service/loader.service';

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
 
    constructor(public loaderService: LoaderService) { }
 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.loaderService.display();//calling method before request go to server
        return next.handle(req).pipe(
        finalize(() => this.loaderService.hide())//calling after getting response
        );
    }
}

Inject the loader-service into loader component constructor for accessing the subject type which is in loader service. Please note here the subject is working like an Observer.

import { Component } from '@angular/core';
import { Subject } from 'rxjs';
import { LoaderService } from '../service/loader.service';


@Component({
  selector: 'app-loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.css']
})
export class LoaderComponent  {
  isLoading: Subject<boolean> = this.loaderService.isLoading;
  
  constructor(private loaderService: LoaderService){}
 
}

In app.componet.html add the loader selector.

<app-loader></app-loader>

In app module configure Interceptor which we have created earlier.

providers: [
    LoaderService,
    {provide:HTTP_INTERCEPTORS,useClass:LoaderInterceptor,multi:true}
  ]

I in this article, I have explained how to create and integrate loader component step by step in an easy manner, I hope you enjoyed this article.

That’s it Folks on this topic. Let us know your comments on this article in the comment box below. Kindly like our facebook page, follows us on twitter and subscribe to our YouTube channel for latest updates.

Leave a Reply