macio.Jun macio.Jun - 17 days ago 15
TypeScript Question

How to cancel recursive ChangeDetectorRef in ngOnDestroy

ngOnInit() {
this.detectChangeInterval = setInterval(
() => {
this.detectRef.detectChanges(); // detectRef is type ChangeDetectorRef
}, 2000);
}

// After leaving this page, I got: error_handler.js:47 EXCEPTION: Attempt to use a destroyed view: detectChanges
ngOnDestroy() {
if(this.detectChangeInterval) {
clearInterval(this.detectChangeInterval);
}
}


I assume the exception means
clearInterval(this.detectChangeInterval);
did not cancel the recursive calling of
this.detectRef.detectChanges();


Any suggestion will be appreciated.

Answer

My suggestion is to use different life cycle events than the default angular2 ones. Ionic2 has its own Page life cycle events which you can use. You can see those here (scroll a bit).

ionViewDidLoad() {
   this.detectChangeInterval = setInterval(() => {
      this.detectRef.detectChanges(); // detectRef is type ChangeDetectorRef
   }, 2000);    
}

ionViewWillLeave() {
   if(this.detectChangeInterval) { 
     clearInterval(this.detectChangeInterval);
   }
}
Comments