[英]Getting the value from a return observable inside catchError
[英]rxjs: how to return the result from another observable from catchError
我正在使用 rxjs 6.5 和 angular。 基本上,我想在我的服務中有一個方法:
這是我到目前為止所擁有的。 我想我需要使用flatMap/mergeMap
,但我不知道如何使用。
服務.ts
public getStatus()
{
return this.http.get('http://api.com/status1')
.pipe(
catchError(() => {
//makes 2nd api call here
return this.http.get('http://api.com/status2')
.pipe(catchError(() =>
{
//both calls failed
return of({
data: 'blah',
success: false
});
}))
}));
}
組件.ts
this.service.getStatus().subscribe(status=>this.status = status);
有人可以幫忙嗎?
您的方法有效,但嵌套管道看起來不太好。 不過,您可以做一件簡單的事情:
// Use 'of' operator to "fake" a successful API call.
// Use 'throwError' operator to "fake" a failed API call.
public getStatus()
{
return of('firstApiCall')
.pipe(
catchError(() => {
//makes 2nd api call here
return of('secondApiCall')
}),
catchError(() =>
{
//both calls failed
return of({
data: 'blah',
success: false
});
})
);
}
您可以提取第二個catchError
塊以將所有運算符都放在一個級別上 - catchError
運算符只會在 observable 引發錯誤時觸發,並且由於您希望對每次調用進行不同的錯誤處理,因此可以這樣做。
可能你也可以只用一個catchError
塊來處理它,並對請求 URL 進行一些檢查以確定你想要返回什么,但我想這需要更多的邏輯並且不值得。
請查看提供的 stackblitz 以查看其實際效果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.