[英]Angular - chaining Observables and combining their results
我想按順序運行以下 2 個請求,最后合並它們的結果。
isSuccessful = false
,則第二個請求不應運行。combineAndPrintMsg()
應該可以成功地處理第一個請求的響應消息。我試過如下所示的嵌套訂閱,但我聽說這不是一個好方法。
firstReq = this.http.get("https://myApi.com/posts?userId=1");
secondReq = this.http.get("https://myApi.com/albums?userId=1");
.....
this.firstReq.subscribe(res1 => {
const secondReqResult = this.doSecondRequest(res1);
this.combineAndPrintMsg(res1, secondReqResult)
})
.....
doSecondRequest(res1: any) {
let secondReqResponse;
if (res1.isSuccessful) {
this.secondReq.subscribe(res2 => {
secondReqResponse = res2;
})
return secondReqResponse;
}
}
combineAndPrintMsg(res1, res2) {
console.log(res1.message + res2.message || '');
}
每個人在開始使用 rxjs 時需要知道的第一件事是不要在可觀察對象中訂閱可觀察對象。 (我過去也一直這樣做)。 有些運算符可以合並您應該學習的可觀察對象的輸出。
在這種情況下,如果第一個結果的isSuccessful為真,我將在pipe內部使用 switchMap 作為第一個可觀察對象來執行第二個。 然后,我將兩個結果合並到第二個請求的 pipe 中 - 除非出現錯誤。 如果是,則使用catchError以便僅返回第一個結果。
firstReq = this.http.get("https://myApi.com/posts?userId=1");
secondReq = this.http.get("https://myApi.com/albums?userId=1");
this.firstReq.pipe(
switchMap((res1) => res1.isSuccessful
? this.secondReq.pipe(
map((res2) => ({ res1, res2 })),
catchError(() => of({ res1, res2: undefined }))
)
: of({ res1, res2: undefined })
),
tap(({ res1, res2 }) => this.combineAndPrintMsg(res1, res2))
);
combineAndPrintMsg(res1, res2) {
console.log(`${res1.message}${res2?.message}`);
}
switchMap的選擇是任意的,您應該了解它與concatMap和mergeMap之間的區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.