Angel Angel
Angel Angel

Reputation: 21728

Angular2 EXCEPTION: Attempt to detect changes on a dehydrated detector

I am having this error EXCEPTION: Attempt to detect changes on a dehydrated detector. and after reading a few online pages. I have not very clear how to fix it or because it is.

https://github.com/angular/angular/blob/e7ad03cba6696fac4eed282ecccd5eb85a36ddb6/modules/angular2/src/core/change_detection/exceptions.ts#L87

The error begins in my case when I put some components while using @RouteConfig RouterLink

and one of my components use this constructor

constructor(http: Http, private ref: ChangeDetectorRef) {
            ..//
            setInterval(() => {
              this.ref.detectChanges();
            }, 5000);

if I comment and change the constructor something like this error disappears

constructor(http: Http) {
                ..//
                /*
                   setInterval(() => {
                     this.ref.detectChanges();
                   }, 5000);
                */

someone to be this, or any alternative to solve it using ChangeDetectorRef

Upvotes: 1

Views: 2162

Answers (2)

NiRUS
NiRUS

Reputation: 4259

Implement the OnDestroy in your component class by importing as below

import { Component, OnDestroy } from '@angular/core';

Then do as below

ngAfterViewInit() { // *Bind when component loads
    console.log('onLoad');
    this.zone.reattach();
}

detectChanges(val: any){ // * Runs outside Angular Code
  /*Your codes and logic*/
  this.intrv = setInterval(()=>{
    this.zone.detectChanges();
  }, 1000)
}

ngOnDestroy() { // * Clean after leave. Clear any intervals or setTimeouts here.
   this.zone.detach();
   if(this.intrv){ //Making sure everything is removed
     clearInterval(this.intrv);
   }
}

Read the code comments for explaination. Above code saved me from the errors.


Explaination:

  • Bind to the change detector API on intialization using ngAfterViewInit()
  • Listen to the Code outside angular and apply changes to the Model
  • When you move out of the view. detach the change Detector using ngOnDestroy()

Documentation:

Upvotes: 0

Angel Angel
Angel Angel

Reputation: 21728

After reading the commentary Eric Martinez. I solved in my case using OnDestroy and detach() in the tests I've done it seems to work well hope it helps others.

    import {Component, ChangeDetectorRef, OnDestroy} from "angular2/core";
    ..//

    export class Test implements OnDestroy{
    ..//

    constructor(http: Http, public ref: ChangeDetectorRef){
    ..//

            setInterval(() => {
              this.ref.detectChanges();
            }, 5000);

    }

    ngOnDestroy(){
      this.ref.detach();
    }

NOTE: I'm new to Angular2 and do not know if this really is the best solution

Upvotes: 3

Related Questions