Angular 2 : Cannot read property 'unsubscribe' of undefined

标签 angular rxjs observable

我正在尝试创建一个计时到特定数字的 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/

相关文章:

angular - 在数组 angular 4 中添加项目

angular - 在 mat-select 上重新选择相同值时触发事件

javascript - mergeAll 是如何工作的?

typescript - RxDB RxCollectionCreator typescript 错误

java - DeferredResult 导致 Weblogic 中的异常

javascript - 在设计 ngrx 状态时对树结构数据进行规范化/非规范化是否有意义?

javascript - 我如何实现 Angular2 时钟

javascript - 订阅 Observable 不触发变更检测

events - FSharp 中的事件和可观察对象

javascript - 从 SPA 捕获或保存动态页面的当前状态(HTML 元素)