停止 Angular2 倒计时

Stop Angular2 CountDown

我想停止我的 Countdown 但它没有停止而且仍然 运行 我有这个 :

import { Subscription } from 'rxjs/Subscription';

sub: Subscription;
countDown;
count;
this.count = 100;
this.countDown = Observable.timer(0, 1000)
        .take(this.count)
        .map(() => this.count = this.count-10);

this.sub = Observable.interval(1000)
        .subscribe((val) => {
            if(this.count===0){
                this.sub.unsubscribe();
            }
        });

当计时器等于 0 时,它会转到 -10,等等...

还有其他方法可以停止该计时器吗?

您没有取消订阅正确的变量。这是你应该怎么做:

this.count = 100;
this.countDown = Observable.timer(0, 1000)
  .subscribe(x => {
      this.count = this.count - 10;
  });

this.sub = Observable.interval(500)
  .subscribe(x => {
     console.log(this.count);
     if (this.count === 0) {
        this.countDown.unsubscribe();
     }
});

Here is a StackBlitz example

我最终创建了一个名为 stopTimer() 的函数,即:

stopTimer(){
        this.countDown = null;
        this.sub.unsubscribe();
}

它将停止 Timer 并将停止 CountDown