Angular2 EXCEPTION: Attempt to detect changes on a dehydrated detector

前端 未结 2 1224
暖寄归人
暖寄归人 2021-01-25 09:15

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 b

2条回答
  •  青春惊慌失措
    2021-01-25 09:42

    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:

    • https://angular.io/docs/js/latest/api/core/index/ChangeDetectorRef-class.html#!#detach-anchor
    • https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#Example

提交回复
热议问题