我使用https://stackoverflow.com/a/39664796/2122303的计时器解决方案,效果很好,除了我的情况,我希望当用户将应用程序放在后台时停止它。
export class Component implements OnInit, OnDestroy {
private tick: string;
private subscription: Subscription;
constructor() {
}
ngOnInit() {
let timer = TimerObservable.create(2000, 1000);
this.subscription = timer.subscribe(t => {
this.tick = t;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
所以我加入了同一个班级
public onDeviceReady() {
document.addEventListener("pause", this.onPause, false);
}
public onPause() {
console.log("device in Pause at ", this.tick)
this.subscription.unsubscribe();
}
并且代码编译得很好,但是当设备进入Pause时,我收到错误: 未捕获的TypeError:无法读取未定义的属性'unsubscribe'
为什么onPause看不到我的this.subscription?