我想停止我的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,等等......
还有另一种方法可以阻止该计时器吗?
答案 0 :(得分:2)
您没有取消订阅正确的变量。这是你应该怎么做:
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();
}
});
答案 1 :(得分:1)
我最终创建了一个名为stopTimer()
的函数:
stopTimer(){
this.countDown = null;
this.sub.unsubscribe();
}
它会停止Timer
并停止CountDown
。