javascript - 更新behaviorsubject中的特定元素,或者只订阅一次

标签 javascript angular rxjs 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$))

关于javascript - 更新behaviorsubject中的特定元素,或者只订阅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642788/

相关文章:

javascript - 本地存储和ngrx存储

angular - RxJS 中的管道有什么用?

angular - RxJS 顺序操作

javascript - 如何从选择框获取值?

javascript - 使用 Cordova 在 iOS 中显示带有外部源的图像

javascript - 在物理上是否可以在没有服务器端语言的情况下将信息写入 JSON 文件?

Angular 语法错误 : Unexpected token P in JSON at position 0

css - Angular 2中/deep/和>>>的使用

javascript - RxJS 检测长时间运行的订阅

javascript - 使用 JS 或 jquery 更改 div ID