angular - 使用 angular 和 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
变量不会简单地更新你的interval
Observable,你必须杀死它并启动一个新的 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
推荐阅读
- docker - Docker 运行和体积说明
- javascript - 在服务器上使用 npm 安装库
- java - Java检查用户名和密码是否匹配(来自xml文件)
- django - 根据是否添加新记录或编辑现有记录在 django 模型中动态设置选项
- android - 如何根据 EditText 的文本隐藏按钮
- php - Symfony 4 动态更改数据库
- java - 将字符串格式转换为列表 - 它不是 json 格式字符串
- javascript - 打印位于图像中的文本
- python - 在滚动函数中确定窗口的函数
- google-calendar-api - 使用 Java Google Calendar API 检索私有日历的私有 iCal url