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;
}
0

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

7 Comments

Can't the http interceptor be used in this case?
Yes, you can Choose that way too
I think it is much more appropriate since he wants to do it on each request, feel free to edit your answer or at least add a note about it.
@PardeepJain, do I need to set that variable on each request's start and completion?
@Ploppy, http interceptor seems to be the best choice for this ..
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.