Angular 角度4:使用HttpClient';s拦截器来设置微调器
这里是我编写的拦截器,它通过拦截器直接处理微调器Angular 角度4:使用HttpClient';s拦截器来设置微调器,angular,Angular,这里是我编写的拦截器,它通过拦截器直接处理微调器 @Injectable() export class ApiInterceptor implements HttpInterceptor { constructor(private _globalSpinnerService: GlobalSpinnerService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<Http
@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
}
}
@Injectable()
导出类ApiInterceptor实现HttpInterceptor{
构造函数(私有_globalSpinnerService:globalSpinnerService){}
截取(req:HttpRequest,next:HttpHandler):可观察{
常量spinnerParam:string=req.params.get(“微调器”)
let handleObs:Observable=next.handle(请求)
if(喷丝头参数){
此.\u globalSpinnerService.spinner=true
handleObs.toPromise()。然后(()=>{
此.\u globalSpinnerService.spinner=false
})
}
返回手柄
}
}
它按预期工作。但是,我现在看到所有涉及微调器的请求都被发送了两次。所以我想我移除旋转器的方法不是最整洁的。我如何告诉我的拦截器在手柄结束后移除微调器
编辑:
我通过替换我的
handleObs.toPromise(),然后用handleObs.do()
来更改代码,现在工作正常。我只是不知道为什么会发生这种情况,因为handleObs
observable是冷的,toPromise
创建一个订阅,然后httpClient(…)。subscribe
创建另一个订阅。这导致了几个请求。是的,应该改用handleObs.do()
,它不会导致订阅,只会产生副作用
通常,最好为微调器设置请求计数器,因为它应该正确处理并发请求:
function spinnerCallback() {
if (globalSpinnerService.requestCount > 0)
globalSpinnerService.requestCount--;
}
if(spinnerParam) {
globalSpinnerService.requestCount++;
handleObs.do(spinnerCallback, spinnerCallback);
}
和globalSpinnerService.spinner
实际上是一个getter:
get spinner() {
this.requestCount > 0;
}
我确实在使用计数器,而不是布尔值:)这只是为了让事情变得更简单,但干杯,伙计!在我的情况下,使用.do
不起作用,我的请求计数也没有减少。@hristonev我建议针对您的具体情况提出一个问题并加以说明。@estus当然。这是一篇很棒的帖子:演示如何实现这一点,并详细解释事情。