什么是 forkJoin 替代方案,允许并行请求在其中一个失败时完成

big*_*haq 1 javascript observable rxjs typescript angular

我想使用并行运行一些请求forkJoin并组合它们的结果,如下所示。但是,当其中一个请求失败时,浏览器会自动取消其余订阅。有什么简单的替代方案可以forkJoin让我并行运行请求,并且如果一个订阅失败,则允许其余订阅完成?

const posts = this.http.get("https://myApi.com/posts?userId=1");
const albums = this.http.get("https://myApi.com/albums?userId=1");

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});

print(res1, res2) {
  const message = res1.text + res2.text;
  console.log(message);
}
Run Code Online (Sandbox Code Playgroud)

Ame*_*mer 5

您可以使用 来实现这一点,但是,您必须单独forkJoin处理每个子的错误,以防止在发生任何错误时取消流。ObservablecatchError

您可以尝试如下操作:

// import { catchError } from 'rxjs/operators';
// import { forkJoin, of } from 'rxjs';

const posts = this.http
  .get('https://myApi.com/posts?userId=1')
  .pipe(catchError((err) => of(err)));
const albums = this.http
  .get('https://myApi.com/albums?userId=1')
  .pipe(catchError((err) => of(err)));

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});
Run Code Online (Sandbox Code Playgroud)