始终在flatMap中调用第二个API



我正在调用 API1 和 API2。从 API1 获取的结果将传递给 API2 的调用。如果对 API1 的调用失败,则应使用空值调用 API2。

this.Api1().pipe(flatMap(result => { 
return this.Api2(result);
})).subscribe( data => {
console.log('Successfully called api 2', data);
});

如何确保即使调用 Api1 失败,也始终调用 API2。

this.Api1().pipe(flatMap(result => { 
return this.Api2(result);
}),
catchError((err: any) => {
console.log('call to api1 failed');
return this.Api2(''); // but the subscribe wont run 
}))
).subscribe( data => {
console.log('Successfully called api 2', data);
});

您应该在flatMap之前移动catchError呼叫:

this.Api1().pipe(
catchError((err: any) => {
console.log('call to api1 failed');
return of(''); // no need to pass this.Api2 here, just emit blank value, flatMap will take it
}),
flatMap(result => {
return this.Api2(result);
}))
.subscribe(data => {
console.log('Successfully called api 2', data);
});

最新更新