[英]How to call an Observable based on outcome of another Observable and return an Observable
[英]How can I have an observable call another one based on the result?
情況:
我有一個 http 請求,一旦我得到它,我需要提出另一個請求。 但是,我提出的第二個請求取決於第一個請求的結果。 如,我的第一個請求返回通過或失敗,如果它返回通過我想調用 apiPass,如果它失敗我想返回一個不同的 Observable。
我知道如果我在第一個電話之后只有一個電話,我可以使用像 mergemap 這樣的東西並編寫類似的東西
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(mergeMap(this.http.get<any>(this.passUrl)));
但我的情況不同 - 我想使用 resPass 來知道我是否應該調用 pass Api,或者我是否應該執行失敗邏輯(它也應該返回一個 Observable,只是一個不同的)。 如果第一個調用參數通過,我如何在沒有不必要的情況下將 map 訂閱到一個 Observable ( http.get(this.passUrl)
),如果參數失敗,如何訂閱另一個 ( otherObservable
)?
在這兩種情況下,我的第一次調用都應該返回http code 200
,因此也不是 http 故障的問題。
有什么線索嗎?
如果我理解你的問題是正確的,我會嘗試這些方面的東西
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(
// concatMap is the preferred operator for typical http operations, see below for more details
concatMap(({id:string, resPass:boolean}) => resPass ?
this.http.get<any>(this.passUrl) :
otherObservable)
);
在處理 http 異步請求時,通常最好使用concatMap
運算符,因為這樣的運算符可確保我們在繼續其他與 observable 相關的異步操作之前收到來自 http 的響應,例如在這種情況下,我們可能會在之后調用另一個 Z880791B3AE70902 Z880791B3AE7002CB88C246876D9FAA8F8Z第一個回來了。
在concatMap
中,我們使用解構(即使用這種形式({id:string, resPass:boolean})
)將預期值的結構定義為第一次調用的返回值,然后根據ressPass
的值,我們執行第二個 http調用或者我們返回otherObservable
,假設這已經在某個地方定義過。
看這篇文章,你可能會得到一些關於 rxjs 和 http 的典型使用模式的靈感。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.