[英]How to put custom gap between interval for polling in Rxjs angular?
[英]Configurable polling interval with angular and rxjs
我正在嘗試使用rxjs和angular創建連續輪詢。 以下是我的要求的實現。
https://stackblitz.com/edit/angular-sq3ke5
ngOnInit() {
const bitcoin$ = this.http.get('https://blockchain.info/ticker');
this.polledBitcoin$ = timer(0, this.timeInterval).pipe(
merge(this.manualRefresh),
concatMap(_ => bitcoin$),
map((response: {EUR: {last: number}}) => {
console.log(new Date() +" >> " + response.EUR.last)
return response.EUR.last;
}),
);
}
但是,在此示例中,我添加了輪詢間隔,並且希望基於用戶輸入的值對其進行更新。 但是,文本輸入中的任何更改都不會反映在輪詢間隔中。 有人可以幫助我達到這個結果嗎?
提前致謝。
更新timeInterval
變量不會簡單地更新您的Observable interval
,您將不得不殺死它並啟動一個新的Observable。
試試這個方法:
<input [ngModel]="timeInterval" (ngModelChange)="changeInterval($event)" />
Bitcoin price: {{ dataToShow }}
ngOnInit() {
this.startInterval();
}
startInterval() {
const bitcoin$ = this.http.get('https://blockchain.info/ticker');
this.polledBitcoin$ = timer(0, this.timeInterval).pipe(
merge(this.manualRefresh),
concatMap(_ => bitcoin$),
map((response: {EUR: {last: number}}) => {
console.log(new Date() +" >> " + response.EUR.last)
return response.EUR.last;
}),
);
this.sub = this.polledBitcoin$.subscribe((data) => {
this.dataToShow = data;
});
}
changeInterval(e) {
this.timeInterval = e;
if (this.sub) {
this.sub.unsubscribe();
}
this.startInterval();
}
https://stackblitz.com/edit/angular-4n29cm?file=app%2Fapp.component.ts
編輯
一種性能更高的方法是等待輸入更改,然后再次重新創建間隔。 我使用了一個主題來監聽輸入中的更改,等待一段時間,以便用戶完成輸入,然后重新啟動間隔。
ngOnInit() {
this.startInterval();
this.inputSub = this.inputSubject.pipe(debounceTime(500)).subscribe(() => {
console.log('restart now')
if (this.intervalSub) {
this.intervalSub.unsubscribe();
}
// you probably don't want an interval running in zero second interval
// add more checks here if you want, for example: this.timeInterval > 200
if (this.timeInterval) {
this.startInterval();
}
})
}
startInterval() {
const bitcoin$ = this.http.get('https://blockchain.info/ticker');
this.polledBitcoin$ = timer(0, this.timeInterval).pipe(
merge(this.manualRefresh),
concatMap(_ => bitcoin$),
map((response: {EUR: {last: number}}) => {
console.log(new Date() +" >> " + response.EUR.last)
return response.EUR.last;
}),
);
this.intervalSub = this.polledBitcoin$.subscribe((data) => {
this.dataToShow = data;
});
}
changeInterval(e) {
console.log("change interval called");
this.timeInterval = e;
this.inputSubject.next(e);
}
https://stackblitz.com/edit/angular-c355ij?file=app%2Fapp.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.