我正在尝试创建一个计时到特定数字的 ObservableTimer
。我已经有这样做的逻辑,但是当我尝试取消订阅时,我得到一个 "Cannot read property 'unsubscribe' of undefined"
错误。
这是我的代码
syncExpireTime() {
let route = AppSettings.API_ENDPOINT + 'Account/ExpireTime'
this.http.get(route, this.options).map(this.extractData).catch(this.handleError).subscribe(
res => {this.expireTime = +res},
error => console.log(error),
() => this.timerSub = TimerObservable.create(0,1000)
.takeWhile(x => x <= this.expireTime)
.subscribe(x => x == this.expireTime ? this.logout() : console.log(x))
)
}
然后这是我的注销代码。我正在尝试在注销时取消订阅过期计时器
logout() {
this.timerSub.unsubscribe()
this.router.navigate(['./login'])
}
最佳答案
有两种方法可以尝试解决此问题。
logout() {
if(this.timerSub){// this if will detect undefined issue of timersub
this.timerSub.unsubscribe();
}
this.router.navigate(['./login'])
}
或者你可以试试 angular 2 的 ngOnDestroy 生命周期钩子(Hook),当我们想销毁我们的组件时,它用来做事
ngOnDestroy() {
if(this.timerSub){
this.timerSub.unsubscribe();
}
this.router.navigate(['./login']);
}
我希望这会有所帮助:)
关于 Angular 2 : Cannot read property 'unsubscribe' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41902534/