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

How to send a POST request via Angular HttpClient wihout cancelling on unsubscribe?

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

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

有什么方法可以在不取消请求的情况下发送请求吗?

使用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 自动完成)。