Angular 2:无法读取未定义的属性'unsubscribe'

Ale*_*ios 6 observable rxjs angular

我正在尝试创建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))
    )
}
Run Code Online (Sandbox Code Playgroud)

然后这是我的注销代码.我在注销时试图取消订阅到期时间

logout() {
    this.timerSub.unsubscribe()
    this.router.navigate(['./login'])
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*mar 12

有两种方法可以尝试解决此问题.

logout() {
    if(this.timerSub){// this if will detect undefined issue of timersub
       this.timerSub.unsubscribe();
      } 
    this.router.navigate(['./login'])
}
Run Code Online (Sandbox Code Playgroud)

或者你可以尝试ngOnDestroy角度2的生命周期钩子,当我们想破坏我们的组件时用来做事情

ngOnDestroy() {
    if(this.timerSub){
       this.timerSub.unsubscribe();
      } 
    this.router.navigate(['./login']); 
 }
Run Code Online (Sandbox Code Playgroud)

我希望这个能帮上忙 :)


Rom*_*n C 2

你应该打电话unsubscribe进来ngOnDestroy

Lyfecicle 挂钩

ngOnDestroy

在 Angular 销毁指令/组件之前进行清理。取消订阅可观察对象并分离事件处理程序以避免内存泄漏。

在 Angular 销毁指令/组件之前调用。