我有 2 個 api 服務呼叫,我將它們壓縮到一個 observable 中:
const firstAPIrequest = this.firstApi.getData();
const secondAPIrequest = this.secondApi.getData();
const combined = zip(firstAPIrequest, secondAPIrequest);
我目前映射這些以回傳一個陣列:
combined.pipe(
map((res) => {
return [res[0], res[1]) // just an example
}
);
然后我將它用作不同組件中的訂閱
combined.subscribe(
(res) => this.handleData(res),
(err) => {
console.debug('Fetch failed', err);
}
)
在這種情況下,如果 API 請求之一失敗,它將顯示錯誤,但我想檢查哪個失敗,例如;如果request1回傳資料并request2失敗,我仍然會從request1
我試過了,catchError但我不認為我可以在這個函式中獲取資料
combined.pipe(
catchError((err) => ...), // how would I catch the data before it throws an error?
map((res) => {
return [res[0], res[1]) // just an example
}
);
uj5u.com熱心網友回復:
要單獨處理來自每個源的錯誤,catchError必須單獨將它們通過管道傳輸到每個源中。catchError必須回傳一個 observable,所以我們將使用 RxJSof函式。
import { of, catchError } from 'rxjs';
const handleError = (error: any) => of({error: error});
const firstAPIrequest = this.firstApi.getData().pipe(
catchError(this.handleError)
);
const secondAPIrequest = this.secondApi.getData().pipe(
catchError(this.handleError)
);
const combined = zip(firstAPIrequest, secondAPIrequest);
現在在訂閱中,您可以檢查回應是否有效或錯誤。
combined.subscribe(
([res1, res2]) => {
if (!!res1.error && !!res2.error) {
// both API calls threw error
} else if (!!res1.error) {
// `firstAPIrequest` threw error
} else if (!!res2.error) {
// `secondAPIrequest` threw error
} else {
// both returned responses
}
}
);
注意:這假設實際回應不包含屬性error。如果是這樣,請將函式中的error屬性替換為handleError其他內容。
uj5u.com熱心網友回復:
您必須在兩個源上捕獲錯誤,因為如果在組合后捕獲錯誤,則組合流將在第一個錯誤后停止。例如:
const replaceErrorWithNull = catchError(() => of(null));
const firstAPIrequest = this.firstApi.getData();
const secondAPIrequest = this.secondApi.getData();
const combined = zip(
firstAPIrequest.pipe(replaceErrorWithNull),
secondAPIrequest.pipe(replaceErrorWithNull)
);
使用這種方法 null 將代替 API 中出錯的資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365770.html
上一篇:Angular5版本升級
下一篇:單擊預覽按鈕時角度改變行顏色
