首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rxjs / Angular 8:在调用Subscription.unsubscribe()时不会触发HTTPHandler

Rxjs / Angular 8:在调用Subscription.unsubscribe()时不会触发HTTPHandler
EN

Stack Overflow用户
提问于 2020-02-05 15:19:18
回答 2查看 51关注 0票数 1

我需要在呼叫过程中使用unsubscribe,但是当我这样做时,没有HttpResponse。这对我来说是个问题,因为我还在使用http拦截器来捕捉何时应该显示加载图标。

因此,在我的特定组件中,我有以下内容:

代码语言:javascript
复制
 if (this.testSubscription)
    this.testSubscription.unsubscribe();  // Stop original http request when calling getTestDetails with other parameters
  this.testSubscription = this.getTestDetails(param1, param2);

我的拦截器:

代码语言:javascript
复制
 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方法来捕获它。任何想法都很受欢迎!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-05 16:32:53

这段代码看起来像vaguely familiar。:D

正如@martin指出的那样,您可以使用finalize运算符。事实上,我已经做了一些测试,发现您甚至不需要tap操作符来处理所有用例:

代码语言:javascript
复制
return next.handle(request).pipe(
  finalize(() => {
    this.totalRequests--;
    if (this.totalRequests === 0) {
      console.log('set loading false');
    }
  })
);

我已经更新了原始答案以反映此信息。

PS:你提出的解决方案可能有一个bug,以防出错。如果您有两个挂起的请求,并且其中一个请求失败,而另一个请求仍在进行中,那么您将让decreaseRequests()运行两次(一个来自catchError操作员,另一个来自finalize),这会将Loading值设置为false,即使还有另一个请求处于挂起状态。

票数 1
EN

Stack Overflow用户

发布于 2020-02-05 16:21:54

多亏了这些评论,我才得以解决我的问题。我已将拦截器更改为:

代码语言:javascript
复制
  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();
  }  }
  )
);

}

我已经对它进行了彻底的测试,它似乎正在为我的目的而工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60070727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档