我使用 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))
最佳答案
您可以捕获
传递给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
,并使用 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))
关于angular - 如何捕捉 Observable.forkJoin(...) 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51103799/