在rxjs中取消订阅

在rxjs中取消订阅,rxjs,unsubscribe,Rxjs,Unsubscribe,我是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; }).un

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

但当删除时,请正确取消订阅其工作

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();
为此:

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

现在,您的请求在收到您想要的响应后被取消订阅。

呼叫是异步的,因此,您的请求甚至在收到响应之前就被取消订阅。我如何取消订阅异步请求您不需要在此处取消订阅。Angular的HttpClient(我假设您正在使用)在发送响应时完成可观察的。一个完整的可观察对象会在其自身之后自动清理。