更新 behaviorsubject 中的特定元素,或者只订阅一次
Update spesific element in behaviorsubject, or only subscribe once
我有一个 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$))
我有一个 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$))