angular 2检测是否有任何RxJS计时器正在运行

时间:2016-12-02 08:42:47

标签: angular timer rxjs scheduler

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

我的应用程序中主要包含2个组件:

1:HomeComponent, 2:MasterComponent。

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

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

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

因此,想要检测是否有任何时间正在运行,然后无法启动,否则启动。

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

主要组件代码:

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

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

无论如何, ngOnInit 我可以检测到任何已经运行的Timer!

1 个答案:

答案 0 :(得分:1)

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();
  }
}