Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Cannot read property 'unsubscribe' of undefined

I am trying to create an ObservableTimer that ticks up to a certain number. I already have logic to do that, but when I try to unsubscribe from it I get a "Cannot read property 'unsubscribe' of undefined" error for it. Here is my code

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))
    )
}

And then here is my logout code. I am trying to unsubscribe from the expiration timer when I log out

logout() {
    this.timerSub.unsubscribe()
    this.router.navigate(['./login'])
}
like image 869
Alex Palacios Avatar asked Jan 27 '17 20:01

Alex Palacios


2 Answers

There are two way which you can try to fix this issue.

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

or you can try ngOnDestroy lifecycle hook of angular 2 which is used to do thing when we want to destroy our component

ngOnDestroy() {
    if(this.timerSub){
       this.timerSub.unsubscribe();
      } 
    this.router.navigate(['./login']); 
 }

i hope this will help :)

like image 161
Amit kumar Avatar answered Sep 27 '22 19:09

Amit kumar


i had faced the same exception. it would better check "subscription.closed == false", before calling the unsubscribe().

ngOnDestroy() {

    // If this.notification has the multiple subscriptions 
    if(this.notifications && this.notifications.length >0)
    {
        this.notifications.forEach((s) => {
            if(!s.closed)    
                s.unsubscribe();
        });        
    }
    // if this.subscription has direct object
    if(this.subscription && !this.subscription.closed)
        this.subscription.unsubscribe();
}
like image 25
babu durairaji Avatar answered Sep 27 '22 21:09

babu durairaji