首页 > 解决方案 > Rxjs 全局任务定时器

问题描述

我正在尝试在我的应用程序上创建一个全局任务计时器。

我正在寻找解决方案: - 当我单击任务的开始进度时,计时器将计数 60 秒。- 但是当我更改页面(另一个组件)并返回上一个时,计时器仍会计数。

你认为冷计时器观察者是个好主意吗?我有实施它的问题。或者,也许 RxJs 有开箱即用的解决方案?

我的意思是-计时器的最佳想法如何持续存在?

谢谢福特的建议。

标签: angulartimerrxjs

解决方案


您可以将计时器 Observable 存储在服务中,确保从服务中订阅它,这样它就不会失去所有订阅者。这些方面的东西:

private timer = interval(1000).pipe(take(60));
private timerStarted = false;

startTimer() {
  this.timer.pipe(
    tap(() => this.timerStarted = true),
    finalize(() => this.timerStarted = false)
  ).subscribe();
}

getTimer() {
  return this.timer;
}

getTimerStarted() {
  return this.timerStarted;
}

然后,在您的组件中:

private destroy$ = new Subject<boolean>();

ngOnInit() {
  if (this.timerService.getTimerStarted()) {
    this.timerService.getTimer().pipe(
      takeUntil(this.destroy$),
      // handle timer stuff here
    ).subscribe();
  }
}

onStartTimer() {
  this.timerService.startTimer();
  this.timerService.getTimer().pipe(
    takeUntil(this.destroy$),
    // handle timer stuff here
  ).subscribe();
}

ngOnDestroy() {
  this.destroy$.next(true);
}

编辑:移动take(60)到 Observable 本身,而不是startTimer方法内部的那个。这应该可以防止它在从外部订阅时计数超过 60 秒。


推荐阅读