angular 2 检测任何 RxJS 计时器是否为 运行

angular 2 detect if any RxJS timer is running or not

我正在开发 angular2 应用程序。我有在预先配置的时间段运行的调度程序要求。

我的应用程序主要有 2 个组件:

1: 主页组件, 2: MasterComponent.

我的主组件将始终存在于浏览器中,所有其他组件都是它的子组件。

现在我在ngOnInit()中添加了RxJS timer..

现在,当我转到 HomeComponent 时,MasterComponent 超出范围,当我回到 MasterComponnent 时,另一次开始(已经第一个开始工作)。所以现在我有 2 个计时器。

所以想检测是否有任何时间是运行然后不开始否则开始。

我只需要在用户登录时开始计时。

主组件代码:

ngOnInit() {
    let timer = Observable.timer(2000, 1000);
    timer.subscribe(this.printConsole);
}

printConsole() {
    console.log("ticks: " + new Date());
}

无论如何,在 ngOnInit 中,我可以检测到任何计时器 运行 或没有!

MasterComponent:

上创建一个静态变量
export class MasterComponent {

  public static TIMER;

  ngOnInit() {
      if(!MasterComponent.TIMER) {
         MasterComponent.TIMER = Observable.timer(2000, 1000);    
      }
  }
}

另一种选择是在您的应用程序中创建单例服务并让该服务创建计时器,这符合我的个人喜好。然后将此服务注入您的 MasterComponent 并订阅计时器。例如:

export class MasterTimer {

   public get timer() {
       return this._timer;
   }

   private _timer;

   constructor() {}

   public initTimer(): void {
      if(!this._timer) {
         this._timer = Observable.timer(2000, 1000);
      }
   }
}

您的 MasterComponent 将更改为:

export class MasterComponent {

  private _timerSub: Subscription;

  constructor(private _masterTimer: MasterTimer){}

  ngOnInit() {
      this._masterTimer.initTimer();
      this._timerSub = this._masterTimer.timer.subscribe(this.printConsole);
  }

  ngOnDestroy() {
      this._timerSub.unsubscribe();
  }
}