我使用
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))
您可能会
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
,并使用 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))
这对我有用:
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 调用也会正常调用
你尝试过这两条线之间的事情吗?
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 也会出错,并且所有其他可观察值将立即取消订阅。
由于
forkJoin
返回一个可观察量,您可以在结果上使用 pipe
运算符以及 catchError
:
Observable.forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson).map((res) => res),
this.http.post<any[]>(URL, jsonBody2, postJson).map((res) => res)
)
.pipe(
catchError(error => {
// handle error
throw error;
})
)
.subscribe(res => this.handleResponse(res))
在这种情况下,如果至少有一个请求失败,将会触发
catchError
回调。