我正在try 实现一个httpService,其中我们有3个Rest API端点.如果第一个API返回成功代码,那么我不想调用下一个端点,但如果出现错误,我想try 第二个或第三个端点. 我写的代码就像
从‘rxjs’导入{of,throwError}; 从‘rxjs/OPERATOR’导入{catchError,mergeMap};
this.httpService
.post(`${primary_system}?id=${params.id}`)
.pipe(
catchError((primaryError) => {
if (!!secondary_system) {
return this.httpService
.post(`${secondary_system}?id=${params.id}`)
.pipe(
catchError((secondaryError) => {
if (!!tertiary_system) {
return this.httpService.post(`${tertiary_system}?id=${params.id}`);
}
return of(secondaryError);
})
);
}
return of(primaryError);
})
);
当然,这将是扁平化这些嵌套调用的一种方式.我认为这是一种不好的做法,不能像这样管可观测到的东西.还有更好的解决方案吗?