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'])
}
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 :)
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With