使用Angular HTTP拦截器管理多个同时的异步服务调用的加载器/旋转器 [英] Manage loader/spinner for multiple simultaneous async service calls using Angular HTTP interceptor

查看:342
本文介绍了使用Angular HTTP拦截器管理多个同时的异步服务调用的加载器/旋转器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have implemented Http Interceptor and showing spinner when service is initiated and hiding spinner when service is 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秒中完成;现在,微调器将在第一个呼叫完成后被隐藏,将无法确认第二个服务呼叫.

For example there are two service calls both occurs at same time; therefore spinner will be shown corresponding to both calls but first service is finished in 2 secs and second in 5 secs; Now spinner will be hidden after the first call is finished, will not be able to acknowledge second service call.

推荐答案

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

I would like to answer my own question, so one can refer to the solution to above question/problem.

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

Firstly, declare a global variable (initialize it as 0) used as a counter for active service calls.

第二,对于每个服务截获的增量计数(计数器变量),当服务调用完成时,递减计数(计数器变量).

Secondly, for each service intercepted increment count(counter variable) and when service call is finalize decrement the count(counter variable).

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

Lastly, if service count is equal to zero hide the spinner else show the spinner.

示例: 通常定义一个拦截器服务以拦截HTTP请求. 在拦截器服务中:

Example: Define an interceptor service in general for intercepting HTTP Requests.After that in interceptor service :

service_count = 0; // counter globally initialized.

constructor(
    private _route:Router
) {}

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

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

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

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

这篇关于使用Angular HTTP拦截器管理多个同时的异步服务调用的加载器/旋转器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆