如何在不取消订阅的情况下通过 Angular HttpClient 发送 POST 请求?

时间:2021-01-07 10:31:53

标签: angular rxjs angular-httpclient

我需要发送一个 POST 请求,我不在乎它是成功还是失败 =>“即发即忘”。发送请求后立即启动硬重定向。这会导致 Angular HttpClient POST 请求被取消。

// sending POST request
this.httpClient.post('someUrl', {}).subscribe();
// hard redirect causes cancelation of POST request
window.location.replace('someOtherUrl');

有没有办法在不取消请求的情况下发送请求?

1 个答案:

答案 0 :(得分:3)

使用finalize

this.httpClient.post('someUrl', {})
  .pipe(finalize(() => window.location.replace('someOtherUrl'))
  .subscribe();

add

this.httpClient.post('someUrl', {})
  .subscribe()
  .add(() => window.location.replace('someOtherUrl'));

Finalize 将针对 nexterror 发出,add 应在取消订阅时调用(HttpClient 自动完成)。