OPV*_*OPV 7 observable rxjs angular
我使用以下代码作为计时器:
export class TimerService {
private ticks: number = 0;
private seconds: number = 0;
private timer;
constructor(seconds: number) {
this.seconds = seconds;
this.timer = Observable.timer(2000, 1000);
this.timer.subscribe(t => {
this.ticks = t;
this.disactivate();
});
}
private disactivate() {
if (this.ticks === this.seconds) {
this.timer.dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试停止计时器时:
this.timer.dispose(); // this.timer.unsubscribe();
Run Code Online (Sandbox Code Playgroud)
它对我不起作用
Jot*_*edo 13
该subscribe方法返回一个Subscription对象,您稍后可以使用该对象来停止侦听您订阅的observable所包含的流.
import { ISubscription } from 'rxjs/Subscription':
import { TimerObservable } from 'rxjs/observable/TimerObservable';
export class TimerService {
private ticks = 0;
private timer$: TimerObservable;
private $timer : ISubscription;
constructor(private seconds = 0) {
this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method
this.$timer = this.timer.subscribe(t => {
this.ticks = t;
this.disactivate();
});
}
private disactivate() {
if (this.ticks >= this.seconds) {
this.$timer.unsubscribe();
}
}
}
Run Code Online (Sandbox Code Playgroud)
重要的是要注意unsubscribe存在于rxjs(版本5及更高版本)中,在此之前,在rx(版本低于5,不同的包)中,该方法被调用dispose
| 归档时间: |
|
| 查看次数: |
11436 次 |
| 最近记录: |