【问题标题】:Unsubscribe in rxjs在 rxjs 中取消订阅
【发布时间】:2018-07-29 10:37:49
【问题描述】:

我是 rxjs 的新手。 订阅方法无法正常工作的这段代码有什么问题。

this.http.postReq(this.api, data)
.subscribe((value) => {
  this.toastr.success(value, "Successfull");
  this.isLoading = false;
}, (err) => {
  this.toastr.error(err.error, "Error")
  this.isLoading = false;
}).unsubscribe();

}

但是当删除“.unsubscribe()”时它可以正常工作。

an example that work correctly in this manner.

【问题讨论】:

  • 调用是异步的,所以你的请求在得到响应之前就被取消订阅了。
  • 如何取消订阅异步请求
  • 这里不需要退订。我假设您正在使用 Angular 的 HttpClient,它会在发送响应时完成 observable。一个完成的 observable 会自动清理。

标签: rxjs unsubscribe


【解决方案1】:

要做到这一点:

let someSubscription = this.http.postReq(this.api, data)
.subscribe((value) => {
  this.toastr.success(value, "Successfull");
  this.isLoading = false;
someSubscription.unsubscribe();
}, (err) => {
  this.toastr.error(err.error, "Error")
  this.isLoading = false;
});

所以现在,您的请求在获得响应(您想要的)后被取消订阅。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-26
    • 2020-10-28
    • 2017-11-21
    • 2021-01-28
    • 2021-11-18
    • 1970-01-01
    • 2016-07-07
    • 2019-03-16
    相关资源
    最近更新 更多