Angular2 Observable Timer Condition

╄→尐↘猪︶ㄣ 提交于 2019-12-05 15:04:44

问题


I have a timer:

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

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

How would I add the condition to after 60 minutes present a popup to the user? I've tried looking at a couple of questions (this and this) but it's not clicking for me. Still new to RxJS patterns...


回答1:


You don't need RxJS for that. You can use good old setTimeout:

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

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

If you really must use RxJS, you could:

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

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



回答2:


Just use observable.timer and subscribe to it.

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




回答3:


I ended up doing this from what I initially had which gives me what I need:

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;
        }
    });
}

I implemented this before I tried what I marked as answer, so will just leave it here.



来源:https://stackoverflow.com/questions/43763430/angular2-observable-timer-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!