javascript - 更新behaviorsubject中的特定元素,或者只订阅一次
问题描述
我有一个BehaviorSubject
每隔 5 秒从我的其他文件中获取持续更新的文件。
但是,有时我不能等待 5 秒才能发生新事件,所以我正在寻找一种方法来仅更新Behaviorsubject
.
我创建了以下内容来处理单个元素:
updateSingleTimer(timer,time,secs = false) {
this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
var newdata = data;
newdata[timer] = time;
this.updateTimers(newdata);
});
}
当然,这将创建一个无限循环,因为一旦updateTimers
调用函数,计时器就会更新。
所以,我只需要在updateSingleTimer
函数中获取计时器数据一次,而不是订阅它。
问:我将如何更改上面的代码,这样它只会得到一次结果this.timers$
?
问:另外,是否有可能以比我目前所做的更简单的方式更新单个元素?
完整代码:
_timers = new BehaviorSubject<any>(null);
private timersChangeSet = new Subject<any>();
constructor(private http: HttpClient, private router: Router) {
this.timersChangeSet.subscribe(val => this._timers.next(val))
}
timers$ = this._timers.asObservable();
updateTimers(object) {
this.timersChangeSet.next(object);
}
updateSingleTimer(timer,time,secs = false) {
// the code will result in infinity loop, of course. but how would i only get the value once?
this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
var newdata = data;
newdata[timer] = time;
this.updateTimers(newdata);
});
}
解决方案
就拿1
this.timers$.pipe(take(1), takeUntil(this._destroyed$))
推荐阅读
- c# - 动态创建的表达式
- r - 计算r中数据框的每日平均值
- javascript - Blazor webassembly:canvas.toDataUrl()?
- javascript - 父节点可以支持其他形状吗?
- html - 粘性页脚引导程序 4 不在底部
- python-3.x - pyTelegramBotAPI 和 Selenium。动态键盘
- css - CSS Grid - 使用 grid-template-columns 而不创建空 div
- angular - Angular 中的链式服务 Observable 调用
- java - 为什么我的 JavaFX 标签的文本出现乱码,如何修复它以显示我请求的字符串?
- redux - material-ui withStyle 不适用于 resux-form