Angular2 可观察定时器条件

2024-04-19

我有一个计时器:

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

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

我如何添加条件以在 60 分钟后向用户显示弹出窗口?我尝试着看几个问题(this https://stackoverflow.com/questions/34728827/rxjs-if-with-observable-as-conditional and this https://stackoverflow.com/questions/42557993/how-do-i-stop-observable-timer-or-observable-interval-automatically-after-ce)但它不适合我。对 RxJS 模式仍然陌生......


你不需要 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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2 可观察定时器条件 的相关文章

随机推荐