Angular4:使用HttpClient的拦截器设置微调器 [英] Angular4: Using HttpClient's interceptor to setup a spinner

查看:131
本文介绍了Angular4:使用HttpClient的拦截器设置微调器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我编写的用于直接通过拦截器处理微调器的拦截器

Here the interceptor I've written to handle the spinner directly via the interceptor

@Injectable()
export class ApiInterceptor implements HttpInterceptor {
    constructor(private _globalSpinnerService: GlobalSpinnerService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const spinnerParam: string = req.params.get("spinner")
        let handleObs: Observable<HttpEvent<any>> = next.handle(req)
        if(spinnerParam) {
            this._globalSpinnerService.spinner = true
            handleObs.toPromise().then(() => {
                this._globalSpinnerService.spinner = false
            })
        }

        return handleObs
    }
}

它正在按预期方式工作.但是,我现在看到我所有涉及微调器的请求都发送了两次.因此,我想我删除微调器的方法不是最干净的.手柄结束后,如何告诉我的拦截器取下旋转器?

It's working as expected. However, I now see all my requests involving the spinner getting sent twice. So I guess my way to remove the spinner isn't the neatest. How can I tell my interceptor to remove my spinner once the handle is over ?

我通过将我的handleObs.toPromise().then替换为handleObs.do()来更改了代码,现在可以正常工作了.我只是不确定为什么

I changed the code by replacing my handleObs.toPromise().then by handleObs.do() and it's now working fine. I am just not sure why

推荐答案

之所以会发生这种情况,是因为handleObs可观察的结果很冷,toPromise创建了一个订阅,然后httpClient(...).subscribe创建了另一个订阅.这导致几个请求.是的,应该使用handleObs.do()代替,它不会导致订阅,只会带来副作用.

This happens because handleObs observable is cold, toPromise creates a subscription, then httpClient(...).subscribe creates another subscription. This results in several requests. And yes, handleObs.do() should be used instead, it doesn't result in subscription and just provides side effect.

通常,最好有一个微调器的请求计数器,因为它应该正确处理并发请求:

Generally it is desirable to have request counter for a spinner, because it should handle concurrent requests properly:

function spinnerCallback() {
  if (globalSpinnerService.requestCount > 0) 
    globalSpinnerService.requestCount--;
}

if(spinnerParam) {
    globalSpinnerService.requestCount++;
    handleObs.do(spinnerCallback, spinnerCallback);
}

globalSpinnerService.spinner实际上是吸气剂:

get spinner() {
  this.requestCount > 0;
}

这篇关于Angular4:使用HttpClient的拦截器设置微调器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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