Angular2可观察定时器条件

时间:2017-05-03 14:50:19

标签: angular timer rxjs observable angular2-observables

我有一个计时器:

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

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

如何在60分钟后将条件添加到用户弹出窗口?我试过看了几个问题(thisthis),但它没有点击我。 RxJS模式还是新手......

3 个答案:

答案 0 :(得分:6)

你不需要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));
}

答案 1 :(得分:6)

只需使用observable.timer并订阅即可。

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

答案 2 :(得分: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;
        }
    });
}

我在尝试将其标记为答案之前实现了这一点,因此请将其保留在此处。