RxJ的后续可观察性:如果发生错误,则继续执行



我需要组合两个api调用-serviceAserviceB。应该在serviceA之后立即调用serviceB。但是,如果serviceA失败,代码应该继续执行并调用serviceB

使用RxJS的正确方法是什么?

以下是我尝试过的:

this.serviceA.getData(id).pipe(
map((data) => {
return { ...data, test: "abc" };
}),
mergeMap((res) => {
return this.serviceB.getData(id).pipe(
map((scores) => this.handleData(scores)),
catchError(() => of(res))
);
})
);

如果您想捕获来自服务A:的错误,则需要将catchError更早地放入管道中

this.serviceA.getData().pipe(
catchError(errA => of(errA)),
map(dataA => ({ ...dataA, test: "abc" })),
switchMap(objA => this.serviceB.getData(objA)),
catchError(errB => of(errB)),
map(dataB => this.handleData(dataB))
);

在上面的代码中,第一个catchError将捕获在对serviceA.getData()的调用中发生的错误,并返回switchMap将接收的可观察到的dataA。执行将继续,因此无论是否发生错误,都会调用serviceB。

第二个catchError将捕获来自serviceB.getData()的错误。

这个交互式StackBlitz演示了这种行为。