两个http调用完成后,我使用Observable.forkJoin()处理响应,但是如果其中一个返回错误,如何捕获该错误?
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))
答案 0 :(得分:22)
您可能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) .map((res) => res)).catch(e => Observable.of('Oops!')),
this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)).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(map((res) => res), catchError(e => of('Oops!'))),
this.http.post<any[]>(URL, jsonBody2, postJson) .pipe(map((res) => res), catchError(e => of('Oops!')))
)
.subscribe(res => this.handleResponse(res))
答案 1 :(得分:1)
这对我有用:
forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson).pipe(catchError(error => of(error))),
this.http.post<any[]>(URL, jsonBody2, postJson)
)
.subscribe(res => this.handleResponse(res))
即使第一次调用发生错误,第二次HTTP调用也将正常调用
答案 2 :(得分:0)
您在这些行之间尝试过什么吗?
const todo1$ = this.myService.getTodo(1);
const error$ = this.myService.getTodo(201);
const todo2$ = this.myService.getTodo(2);
forkJoin([todo1$, error$, todo2$])
.subscribe(
next => console.log(next),
error => console.log(error)
);
请记住,如果在某个时间点任何输入可观察到的错误,forkJoin也将错误,并且所有其他可观察到的对象将立即被取消订阅。