0

I want to show loader on each service call in angular. I am using ngx-loading.

I have tried below code but it works only on route change, not getting the way to get it solved.

import { LoadingModule, ANIMATION_TYPES } from 'ngx-loading';
<router-outlet (activate)="onActivate($event)"></router-outlet>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '14px' }"></ngx-loading>

public loading = false;

onActivate(e) {
   this.loading = true;
}
Sunil Kumar
  • 909
  • 2
  • 17
  • 31

1 Answers1

0

There are 2 options for you,

You could use an HTTP Interceptor to intercept http request without modifying and update the state of your loader when a request starts and finishes.

Here is a basic interceptor which just let the request pass without any modification.

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Do your stuff here
    return next.handle(req);
  }
}

To provide your interceptor in your module, add this to your providers array:

{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },

NB: You will probably need to inject a custom service in the interceptor to communicate the state of your loader to the components using it.

More info https://angular.io/guide/http#intercepting-requests-and-responses


Or use a shared service for all the HTTP requests and in the start of request make some variable value true which will bind to your loader and after completion of request make it false which will hide your loader from DOM.

For example

httpCall() {
this.loading = true;
return this.http.post(url, data, { headers: headers })
  .do(data=> {this.loading = false;},
  err=> {this.loading = false;);
}

<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '14px' }"></ngx-loading>
Ploppy
  • 14,810
  • 6
  • 41
  • 58
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215