我需要在呼叫过程中使用unsubscribe,但是当我这样做时,没有HttpResponse。这对我来说是个问题,因为我还在使用http拦截器来捕捉何时应该显示加载图标。
因此,在我的特定组件中,我有以下内容:
if (this.testSubscription)
this.testSubscription.unsubscribe(); // Stop original http request when calling getTestDetails with other parameters
this.testSubscription = this.getTestDetails(param1, param2);我的拦截器:
intercept(request: HttpRequest<any>, next: HttpHandler) {
this.totalRequests++;
console.log(' intercept totalRequests: ', this.totalRequests);
this.loadingService.isLoading.next(true);
return next.handle(request).pipe(
tap(res => {
if (res instanceof HttpResponse) {
// I need to get here even when unsubscribing !!!!
this.decreaseRequests();
}
}),
catchError(err => {
this.decreaseRequests();
throw err;
})
);
}因此,当我在订阅上执行unsubscribe时,我真的不确定如何触发我的intercept方法来捕获它。任何想法都很受欢迎!
发布于 2020-02-05 16:32:53
这段代码看起来像vaguely familiar。:D
正如@martin指出的那样,您可以使用finalize运算符。事实上,我已经做了一些测试,发现您甚至不需要tap操作符来处理所有用例:
return next.handle(request).pipe(
finalize(() => {
this.totalRequests--;
if (this.totalRequests === 0) {
console.log('set loading false');
}
})
);我已经更新了原始答案以反映此信息。
PS:你提出的解决方案可能有一个bug,以防出错。如果您有两个挂起的请求,并且其中一个请求失败,而另一个请求仍在进行中,那么您将让decreaseRequests()运行两次(一个来自catchError操作员,另一个来自finalize),这会将Loading值设置为false,即使还有另一个请求处于挂起状态。
发布于 2020-02-05 16:21:54
多亏了这些评论,我才得以解决我的问题。我已将拦截器更改为:
intercept(request: HttpRequest<any>, next: HttpHandler) {
this.totalRequests++;
this.loadingService.isLoading.next(true);
return next.handle(request).pipe(
tap(res => {
//Removed code here
}),
catchError(err => {
this.decreaseRequests();
throw err;
}),
finalize(() => {
if(this.totalRequests > 0){
this.decreaseRequests();
} }
)
);}
我已经对它进行了彻底的测试,它似乎正在为我的目的而工作。
https://stackoverflow.com/questions/60070727
复制相似问题