Angular2可观察定时器条件

Mil*_*ilo 12 timer observable rxjs angular2-observables angular

我有一个计时器:

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

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

如何在60分钟后向用户添加弹出窗口?我已经尝试过看几个问题(这个这个),但它不是为了点击我.RxJS模式还是新手......

Wil*_*ill 7

你不需要RxJS.你可以用好旧的setTimeout:

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

    this.timer = setTimeout(this.showPopup.bind(this), 60 * 60 * 1000);
}
Run Code Online (Sandbox Code Playgroud)

如果你真的必须使用RxJS,你可以:

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

    this.timerSub = Rx.Observable.timer(60 * 60 * 1000)
        .take(1)
        .subscribe(this.showPopup.bind(this));
}
Run Code Online (Sandbox Code Playgroud)


Bha*_*han 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");
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

请查看更多详情

  • 您还需要退订。最好将上面的代码放在ngOnInit()中,然后退订ngOnDestroy() (2认同)