如何在 angular 中的每个服务调用中显示加载程序

how to show loader on each service call in angular

我想在 angular 中的每个服务调用中显示加载程序。我正在使用 ngx-loading。

我试过下面的代码,但它只适用于路线变化,没有找到解决问题的方法。

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

有 2 个选项供您选择,

您可以使用 HTTP 拦截器 来拦截 http 请求,而无需在请求开始和完成时修改和更新加载程序的状态。

这是一个基本的拦截器,它只是让请求通过而不做任何修改。

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

要在模块中提供拦截器,请将其添加到 providers 数组:

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

注意:您可能需要在拦截器中注入自定义服务,以将加载器的状态传达给使用它的组件。

更多信息https://angular.io/guide/http#intercepting-requests-and-responses


或者对所有 HTTP 请求使用 共享服务,并在请求开始时将一些变量值设置为 true,它将绑定到您的加载程序,并在请求完成后将其设置为 false这将从 DOM.

隐藏你的装载机

例如

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>