[英]How to manually refresh a rxjs timer and update parameters of the observable?
我正在對網頁進行分頁,顯示每 2 分鍾從 API 更新的數據(API 已分頁,但我需要自己進行分頁以根據需要顯示數據,例如:每頁 100 個元素,頁碼 5 ,這將顯示從 401 到 500 的元素)。
private readonly _start = new Subject<void>();
private readonly _stop = new Subject<void>();
lista : any = [];
pNum = 1;
act = timer(0, 120000);
constructor(private ListaService:ListaService) {
this.act.subscribe(() => {
this.ListaService.getLista(this.pNum,'usd').pipe(
takeUntil(this._stop),
repeatWhen(() => this._start)
).subscribe(resp=>{
this.lista = resp
});
})
}
start(): void {
document.body.scrollTop = 0;
this._start.next();
}
stop(): void {
this._stop.next();
}
所以問題是,當我單擊按鈕更改頁面時,會調用 stop() 和 start() 方法,並且變量 pNum 也會更新為所選頁面的編號。 我認為這樣做會加載所選頁面的數據,但它沒有發生,數據在計時器觸發時單擊頁碼后 2 分鍾更新。
有沒有辦法手動刷新定時器並更新可觀察的參數?
是的,修改您的act
以包含“手動”更新的來源,因此:
manual$ = new Subject<void>();
act = merge(timer(0, 120000), this.manual$)
然后,每當您需要手動更新時,請在manual$
上調用next
:
this.manual$.next();
編輯
雖然我們在這里,但不要嵌套subscribe
調用 - 使用扁平操作符( switchMap
在這種情況下是合適的),因此:
this.act
.pipe(switchMap(_ => this.ListaService.getLista(this.pNum,'usd')))
.subscribe(resp => this.lista = resp);
有關演示,請參閱stackblitz 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.