【问题标题】:Rxjs / Angular 8: HTTPHandler doesn't get triggered when calling Subscription.unsubscribe()Rxjs / Angular 8:调用 Subscription.unsubscribe() 时不会触发 HTTPHandler
【发布时间】:2020-02-05 07:19:17
【问题描述】:

我需要在通话过程中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 时,我不确定如何触发我的拦截方法来捕捉它。 任何想法表示赞赏!

【问题讨论】:

  • 您可以使用finalize,它在您退订时也会触发,但在这种情况下,您将无法访问任何next,以防它成功通过。
  • 一般情况下,您可以使用switchMap 平滑地取消订阅一个流并订阅另一个流。
  • Martin 的评论很容易解决,感谢大家的帮助!

标签: angular rxjs httprequest


【解决方案1】:

此代码看起来像vaguely familiar。 :D

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

return next.handle(request).pipe(
  finalize(() => {
    this.totalRequests--;
    if (this.totalRequests === 0) {
      console.log('set loading false');
    }
  })
);

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

PS:如果出现错误,您提出的解决方案可能存在错误。如果您有两个待处理的请求,其中一个失败而另一个仍在进行中,您将让decreaseRequests() 运行两次(一个来自catchError 运算符,一个来自finalize),这会将加载设置为@ 987654328@ 即使还有另一个请求待处理。

【讨论】:

  • 哦,好的,你能指出这一点!这也将是一个更清洁的解决方案。谢谢!
【解决方案2】:

感谢 cmets,我能够解决我的问题。 我已将拦截器更改为:

  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();
  }  }
  )
);

}

我已经对其进行了彻底的测试,它似乎符合我的目的。

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 2017-09-02
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2020-04-11
    • 2023-03-12
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多