import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http' import { Observable } from 'rxjs'; import { finalize } from 'rxjs/operators'; import { NgxSpinnerService } from 'ngx-spinner'; @Injectable() export class LoaderInterceptor implements HttpInterceptor { constructor(private spinner: NgxSpinnerService) { } requestCounter = 0; // Identifies and handles a http request intercept(req: HttpRequest, next: HttpHandler): Observable> { // Handles a http request for showing and hiding the loading panel. this.beginRequest(); return next.handle(req).pipe( finalize(() => { this.endRequest(); }) ); } // Increments the request counter when any api is called and hides the loading panel. beginRequest() { this.requestCounter = Math.max(this.requestCounter, 0) + 1; if (this.requestCounter === 1) { this.spinner.show(); } } // Decrements the request counter when any api is completed and hides the loading panel. endRequest() { this.requestCounter = Math.max(this.requestCounter, 1) - 1; if (this.requestCounter === 0) { this.spinner.hide(); } } }