ANGULAR:从Timer Observable取消订阅后注入另一个函数

时间:2017-08-31 20:31:08

标签: angular typescript rxjs observable ionic3

我正在创建一个考试应用程序,所以当时间到了,我需要一个视图控制器来弹出告诉用户他已超出他的时间并带他/她到结果页面!!

但是在取消订阅计时器后,我的功能进入循环!!!

拜托,我需要帮助...

我的代码如下!

minutesDisplay: number = 0;
hoursDisplay: number = 0;
secondsDisplay: number = 0;

sub: Subscription;

showAlert() {
    let alert = this.alertCtrl.create({

      subTitle: 'Ooops, Time Up! ',
    });
    alert.present();
    this.activity.openModal();
  }

ngOnInit() {
    this.startTimer();
}

public ngOnDestroy() {
    if (this.minutesDisplay == 1){
        this.sub.unsubscribe();
    }

    return true;

}

private startTimer() {
    let timer = Observable.timer(1, 1000);
    this.sub = timer.subscribe(
        t => {
            this.ticks = t;
            this.secondsDisplay = this.getSeconds(this.ticks);
            this.minutesDisplay = this.getMinutes(this.ticks);
            this.hoursDisplay = this.getHours(this.ticks);
            this.ngOnDestroy();
        }
    ); 
    this.showAlert();
 }

2 个答案:

答案 0 :(得分:1)

我没试过......但你可以尝试以下方法:

public ngOnDestroy() {
    this.sub.unsubscribe();  // Stop the timer if the user navigates elsewhere
}

private startTimer() {
    let timer = Observable.timer(1, 1000);
    this.sub = timer.subscribe(
        t => {
            this.ticks = t;
            this.secondsDisplay = this.getSeconds(this.ticks);
            this.minutesDisplay = this.getMinutes(this.ticks);
            this.hoursDisplay = this.getHours(this.ticks);
            if (this.minutesDisplay == 1){
               this.sub.unsubscribe();  // Stop the timer when time is up.
               this.showAlert();        // Show the alert now
            }
        }
    ); 
 }

答案 1 :(得分:0)

Observable.timer(1, 1000)
  .map(t=>this.getMinutes(t) === 1) // Observable<tick> -> Observable<boolean>
  .first(istimeUp => istimeUp) // take first Observable<true>
  .subscribe(()=>this.showAlert())