我有一个计时器:
initiateTimer() {
if (this.timerSub)
this.destroyTimer();
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe(t => {
this.secondTicks = t
});
}
如何在60分钟后将条件添加到用户弹出窗口?我试过看了几个问题(this和this),但它没有点击我。 RxJS模式还是新手......
答案 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");
});
}
}
答案 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;
}
});
}
我在尝试将其标记为答案之前实现了这一点,因此请将其保留在此处。