[英]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.