[英]angular 2 detect if any RxJS timer is running or not
I am working on angular2 application. 我正在研究angular2应用程序。 I have scheduler requirement that runs on period of pre-configured time.
我有在预定时间段内运行的调度程序要求。
I have mainly 2 component in my application: 我的应用程序主要有2个组件:
1: HomeComponent, 2: MasterComponent. 1:HomeComponent,2:MasterComponent。
My master component will always be there in browser, all other component are it's child component of it. 我的主组件将始终存在于浏览器中,所有其他组件都是其子组件。
Now I have added RxJS timer
in ngOnInit()
.. 现在,我在
ngOnInit()
添加了RxJS timer
。
Now when I go to HomeComponent, MasterComponent is out of scope and when I came back to MasterComponnent another times starts(already first is working).. So Now I have 2 timers. 现在,当我转到HomeComponent时,MasterComponent已超出范围,当我回到MasterComponnent时,又有一次启动(已经开始工作了)。.现在我有2个计时器。
So want to detect if any times is running then not start otherwise start. 因此,要检测是否有任何时间在运行,则不要启动,否则请启动。
I need to start times only when user logs in. 我仅在用户登录时才需要启动时间。
Master Component Code: 主组件代码:
ngOnInit() {
let timer = Observable.timer(2000, 1000);
timer.subscribe(this.printConsole);
}
printConsole() {
console.log("ticks: " + new Date());
}
is there anyway so in ngOnInit I can detect any Timer already running or not ! 无论如何,所以在ngOnInit中我可以检测到任何已经运行的Timer!
Create a static variable on your MasterComponent
: 在您的
MasterComponent
上创建一个静态变量:
export class MasterComponent {
public static TIMER;
ngOnInit() {
if(!MasterComponent.TIMER) {
MasterComponent.TIMER = Observable.timer(2000, 1000);
}
}
}
Another option, and this has my personal preference, could be to create a singleton service in your application and let that service create the timer. 另一个选择(这是我个人的喜好)可能是在您的应用程序中创建单例服务,然后让该服务创建计时器。 Then inject this service into your
MasterComponent
and subscribe to the timer. 然后将此服务注入您的
MasterComponent
并订阅计时器。 For example: 例如:
export class MasterTimer {
public get timer() {
return this._timer;
}
private _timer;
constructor() {}
public initTimer(): void {
if(!this._timer) {
this._timer = Observable.timer(2000, 1000);
}
}
}
Your MasterComponent
will change to this: 您的
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.