2017-05-03 70 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; 
     } 
    }); 
} 

我實現了這個之前我試了一下我標記爲答案,所以會只是把它留在這裏。