2017-05-03 68 views
3

我有一个计时器:Angular2可观察定时器条件

initiateTimer() { 
    if (this.timerSub) 
     this.destroyTimer(); 

    let timer = TimerObservable.create(0, 1000); 
    this.timerSub = timer.subscribe(t => { 
     this.secondTicks = t 
    }); 
} 

我怎么会弹出一个用户当前60分钟后加入的条件?我试过看几个问题(thisthis),但它不是为我点击。 RxJS模式还是新的...

回答

3

您不需要RxJS。你可以用好老setTimeout

initiateTimer() { 
    if (this.timer) { 
     clearTimeout(this.timer); 
    } 

    this.timer = setTimeout(this.showPopup.bind(this), 60 * 60 * 1000); 
} 

如果你真的必须使用RxJS,你可以:

initiateTimer() { 
    if (this.timerSub) { 
     this.timerSub.unsubscribe(); 
    } 

    this.timerSub = Rx.Observable.timer(60 * 60 * 1000) 
     .take(1) 
     .subscribe(this.showPopup.bind(this)); 
} 
5

Rxjs是在JavaScript中非常importent库。 Rxjs广泛用于Angular。

import { Component } from '@angular/core'; 
import { Observable } from 'rxjs/Rx'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
}) 
export class AppComponent { 
    title = 'app works!'; 

    constructor(){ 
    var numbers = Observable.timer(10000); // Call after 10 second.. Please set your time 
    numbers.subscribe(x =>{ 
     alert("10 second"); 
    }); 
    } 
} 

Please see more details

+0

您还需要退订。最好在ngOnInit()中放置上面的代码,并在ngOnDestroy()中取消订阅 – user2960993

0

我结束了,从我最初有这给了我这样做,我需要什么:

initiateTimer() { 
    if (this.timerSub) 
     this.destroyTimer(); 

    let timer = TimerObservable.create(0, 1000); 
    let hour = 3600; 
    this.timerSub = timer.subscribe(t => { 
     this.secondTicks = t; 
     if (this.secondTicks > hour) { 
      alert("Save your work!"); 
      hour = hour * 2; 
     } 
    }); 
} 

我实现了这个之前我试了一下我标记为答案,所以会只是把它留在这里。