使用 Angular HTTP 拦截器管理 loader/spinner 多个同步异步服务调用

Manage loader/spinner for multiple simultaneous async service calls using Angular HTTP interceptor

我已经实现了 Http 拦截器并在服务启动时显示微调器并在服务启动时隐藏微调器 success/fails。

代码示例:

        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 秒 内完成;现在微调器会在第一次调用完成后隐藏,将无法确认第二次服务调用。

我想回答我自己的问题,所以可以参考上面question/problem的解决方法。

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

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

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

示例: 定义一个通用的拦截器服务来拦截 HTTP Requests.After 在拦截器服务中:

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