如何捕获 Observable.forkJoin(...) 中的错误?

2023-12-31

I use Observable.forkJoin()在两个 HTTP 调用完成后处理响应,但如果其中任何一个返回错误,我该如何捕获该错误?

Observable.forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res),
  this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)
)
.subscribe(res => this.handleResponse(res))

You may catch您传递给的每个可观察量中的错误forkJoin:

// Imports that support chaining of operators in older versions of RxJS
import {Observable} from 'rxjs/Observable';
import {forkJoin} from 'rxjs/add/observable/forkJoin';
import {of} from 'rxjs/add/observable/of';
import {map} from 'rxjs/add/operator/map';
import {catch} from 'rxjs/add/operator/catch';

// Code with chaining operators in older versions of RxJS
Observable.forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson).catch(e => Observable.of('Oops!')),
  this.http.post<any[]>(URL, jsonBody2, postJson).catch(e => Observable.of('Oops!'))
)
.subscribe(res => this.handleResponse(res))

另请注意,如果您使用RxJS6,则需要使用catchError代替catch, and pipe运算符而不是链接。

// Imports in RxJS6
import {forkJoin, of} from 'rxjs';
import {map, catchError} from 'rxjs/operators';

// Code with pipeable operators in RxJS6
forkJoin(
  this.http.post<any[]>(URL, jsonBody1, postJson).pipe(catchError(e => of('Oops!'))),
  this.http.post<any[]>(URL, jsonBody2, postJson).pipe(catchError(e => of('Oops!')))
)
  .subscribe(res => this.handleResponse(res))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何捕获 Observable.forkJoin(...) 中的错误? 的相关文章

随机推荐