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
.
this.cdRef.detectChanges();
do you getExpressionChangedAfterCheck
error ? – Babinwhile
loop imagine how many times you are subscribing to yourObservable
, what's the purpose in every iteration update values of propertiesuser
andloading
inside subscription ? – BabinmarkForCheck
instead ofdetectChanges
. – Christinachristinezone.run
is another way to fix this exception #36919899 – Christinachristine