首页 > 解决方案 > 使用 Angular HTTP 拦截器管理多个同时异步服务调用的加载器/微调器

问题描述

我已经实现了 Http 拦截器并在服务启动时显示微调器,并在服务成功/失败时隐藏微调器。

代码示例:

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

             return next.handle(req).pipe(
                tap((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse && event.body.errCode != undefined) {
                        // show_spinner

                    }
                }),
                finalize(()=>{
                    // hide_spinner
             })
         }

例如,有两个服务调用同时发生;因此微调器将显示对应于两个调用,但第一个服务在2 秒内完成,第二个在5 秒内完成;现在微调器将在第一次调用完成后隐藏,将无法确认第二次服务调用。

标签: angularrxjshttprequestinterceptorangular-http-interceptors

解决方案


我想回答我自己的问题,因此可以参考上述问题/问题的解决方案。

首先,声明一个全局变量(初始化为 0)用作活动服务调用的计数器。

其次,对于每个服务拦截的增量计数(计数器变量),当服务调用完成时,减少计数(计数器变量)。

最后,如果服务计数为零,则隐藏微调器,否则显示微调器。

示例:定义一个拦截器服务来拦截 HTTP 请求。之后在拦截器服务中:

service_count = 0; // initialize the counter.

constructor(
    private _route:Router
) {}

intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

  this.service_count++; // increment the count for each intercepted http request.
  // show spinner.

    return next.handle(req).pipe(
                finalize(() => {
                    this.service_count--;
                 // decrement when service is completed (success/failed both 
                    handled when finalize rxjs operator used)

                    if (this.service_count === 0) {
                        // hide spinner
                    }
                })
            );
}

推荐阅读