[英]Rxjs : Retry http call with updated parameters if no results
我是Rxjs的新手,我正在嘗試向我的 API 發出請求,並在參數中傳遞了限制。 我的問題是有時由於某些原因返回的結果為空。 我需要做的是用更新的參數重試這個 API 調用(跳過參數)
pollService.getPoll$(skip, limit).subscribe((pollList) => {
doStuff;
},
(error) => {
doStuff;
});
我讀了一些有關重試的話題,當時Z8308CE7C9AC196C1131CE17D2FB1E78255Z ZC1C425268E68385D1AB5074C174C17A94F14F14F14Z,但您不想重新播出,但我不想重新播出,但我不想重新播放錯誤,我不想重新播放IRRORS,而我卻不願意進行錯誤,而我卻不願意進行錯誤。但對我來說不是很清楚。
有人可以解釋我在這里做什么!
謝謝
亞歷克斯
考慮使用如下所示的擴展運算符:
import { EMPTY, of } from "rxjs"
import { expand } from "rxjs/operators"
public startPolling(skip: number, limit: number): void {
of([])
.pipe(
expand(x => x.length < 2 ? pollService.getPoll$(skip--, limit) : EMPTY)
)
.subscribe(pollList => {})
}
更新:
public poll = (skip: number, limit: number): void => {
defer(() => getPoll$(1 + skip--, limit))
.pipe(
repeat(),
first(x => {
if(x.length < 2){
// update some variable in the component
return false;
}
return true;
})
)
.subscribe(pollList => { })
}
如果我理解正確,您的后端是使用skip
和limit
參數分頁數據。
所以,如果你有一個過高的skip
值,你想自動減少它。
RxJS中有很多很多方法可以解決這個問題:
getPoll$
之后插入switchMap
。 SwitchMap
將返回一個新的 observable,如果結果正常則包裝結果(使用of(pollList)
),或者返回pollService.getPoll$(newSkipValue, newLimitValue)
map
結果並在結果未通過驗證時拋出錯誤。 然后你可以catchError
並將新調用的結果返回給getPoll$
但是,我建議以不同的方式對調用進行建模。 我會使用Subject
作為請求的來源,並switchMap
來執行請求。
// inside the component or service
interface GetPollRequest {
skip: number;
limit: number;
}
private _callSource = new Subject<GetPollRequest>();
public triggerCall(skip: number, limit: number) {
this._callSource.next({skip, limit});
}
constructor(...) {
this._callSource.pipe(
// every time _callSource emits, we call the server
switchMap(({skip, limit) => pollService.getPoll$(skip, limit).pipe(
map(pollList => ({ pollList, skip, limit }))
),
tap(({pollList, skip, limit}) => {
// update the request in any way you need. You need to make sure
// that the next automatic trigger doesn't repeat indefinitely,
// or you'll simulate a DOS attack to your backend
if (pollList.length < 2) this.triggerCall(skip - 2, limit);
})
).subscribe(pollList => // update the component status);
}
使用此模式,您將主題用作觸發器(或自定義事件,它們幾乎相同),並在構造函數期間將它們包裝起來。
SwitchMap
用於在每次源發出時創建一個 observable(在這種情況下,執行請求)。 Tap
用於執行操作(很像訂閱),嵌入在 pipe 內的轉換鏈中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.