【问题标题】:Angular2 Observable Timer ConditionAngular2 可观察定时器条件
【发布时间】:2017-10-01 11:38:21
【问题描述】:

我有一个计时器:

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

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

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

【问题讨论】:

    标签: angular timer rxjs observable angular2-observables


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      只需使用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

      【讨论】:

      • 你也需要退订。最好将上面的代码放在 ngOnInit() 中,并在 ngOnDestroy() 中取消订阅
      【解决方案3】:

      我最终以我最初拥有的东西来做这件事,这给了我我需要的东西:

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

      我在尝试我标记为答案的内容之前实现了这一点,所以将它留在这里。

      【讨论】:

      • 你好吗destroyTimer()?
      • @genuinefafa if (this.timerSub) this.timerSub.unsubscribe();
      猜你喜欢
      • 2018-05-20
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2017-01-29
      • 2023-03-25
      相关资源
      最近更新 更多