Angular 7: ChangeDetectorRef detectChanges() causes infinite loop when called from inside a subscription

ぃ、小莉子 提交于 2019-12-31 06:53:07

问题


I am posting here after reading all the material related to change detection and similar post and failing to solve my problem.

ChangeDetectorRef detectChanges() causes infinite loop when called from inside a subscription. If I don't call detectChanges, I get ExpressionChangedAfterCheck error. I seriously don't know how to solve, and why is the ExpressionChangedAfterCheck error comes

ngAfterViewInit() {
    this.route.params.subscribe((params) => {
      this.userId = params.userId;
      if (this.userId != undefined) {
        this.loadActivity();
      }
      else {
        alert("Userid not supplied");
      }
      this.cdRef.detectChanges();
    });
  }

  loadActivity() {
    while(this.layers.length > 0){
      this.layers.pop();
    }
    this.loading = true;
    this.userService.authenticatedGet(ApiUrls.GetLocation(this.userId, this.activity.from.getTime(), this.activity.to.getTime()), {}).subscribe(
      (res:any) => {
        this.user = res.user;
        this.loading = false;
        // other logic
        this.cdRef.detectChanges();
        console.log("Loading is " + this.loading);
      }
    );
  }

Note: This problem is there only when the value is bound with ngIf.


回答1:


I resolved this. Issue was not with the lifecycle but with a directive leaflet from ngx-leaflet project.

When I removed leaflet related directive and bindings all errors vanished.

Error came even with this as well:

<ng-container *ngIf="!loading">
    <div
      class="map"
      leaflet
      (leafletMapReady)="onMapReady($event)"
      [leafletOptions]="options"
      [leafletLayers]="layers"
      [leafletLayersControl]="layersControl">
    </div>
</ng-container>

I tried adding detectChanges and markForCheck alternatively, but again got no luck.

  onMapReady(map: Map) {
    this.map = map;
    setTimeout(() => map.invalidateSize(), 1000);
    this.route.params.subscribe(params => {
      this.userId = params["userId"];
      this.loadActivity();
    });
    this.cdRef.markForCheck();
  }

Finally, I ditched leaflet while writing this answer, and I am going to try Angular-Google-Maps.

And yeah A-G-M is working fine.



来源:https://stackoverflow.com/questions/53467529/angular-7-changedetectorref-detectchanges-causes-infinite-loop-when-called-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!