Angular-Interceptor:如何管理页面上的多个加载器/旋转器

时间:2018-11-27 13:21:58

标签: javascript angular rxjs angular-http angular-http-interceptors

我们有一个Angular6应用程序,在页面上我们有不同的组件,并且每个组件都有<loader isLoading={loading} />以便在进行API调用时显示加载程序。但是这个过程是手动的,为此每个组件都必须维护加载标志。

我希望 拦截器 进行处理。我已经编写了代码,但是部分正常。

应用行为

enter image description here

在我的实现中,除非每个API调用完成,否则它将一直显示加载程序。 (保持API调用的数量)

所以我怎么 仅显示那些尚未完成API调用的加载程序,并隐藏那些已完成API的加载程序

拦截器实现

export class HttpCommonInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.loader.start();
        this.loaderCount++;
        return next.handle(req).pipe(
            tap(event => {
                if (event instanceof HttpResponse) {
                    this.loaderCount--;
                    if (this.loaderCount === 0) {
                        this.loader.stop();
                    }
                    return of(event);
                }
            }),
            catchError(error => {
                this.loader.stop();
                this.loaderCount--;
                console.log('Error caught in interceptor ', error);
                return of(error);
            })
        );
    }
}

0 个答案:

没有答案
相关问题