how to show loader on each service call in angular [duplicate]

亡梦爱人 提交于 2020-01-16 19:48:46

问题


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

回答1:


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>


来源:https://stackoverflow.com/questions/50699435/how-to-show-loader-on-each-service-call-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!