Angular 7:从订阅内部调用时,ChangeDetectorRef detectChanges()导致无限循环 [英] Angular 7: ChangeDetectorRef detectChanges() causes infinite loop when called from inside a subscription
问题描述
在阅读了所有与变更检测和类似帖子相关的材料之后,我在这里发布了内容,但未能解决我的问题.
I am posting here after reading all the material related to change detection and similar post and failing to solve my problem.
ChangeDetectorRef detectChanges()
会导致无限循环.如果我不打电话给detectChanges
,我会收到ExpressionChangedAfterCheck
错误.我真的不知道该怎么解决,为什么会出现ExpressionChangedAfterCheck
错误
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);
}
);
}
注意:仅当值与ngIf
绑定时,才会出现此问题.
Note: This problem is there only when the value is bound with ngIf
.
推荐答案
我解决了这个问题.问题不是生命周期,而是ngx-leaflet项目中的指令leaflet
.
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.
错误也随之出现:
<ng-container *ngIf="!loading">
<div
class="map"
leaflet
(leafletMapReady)="onMapReady($event)"
[leafletOptions]="options"
[leafletLayers]="layers"
[leafletLayersControl]="layersControl">
</div>
</ng-container>
我尝试过交替添加detectChanges和markForCheck,但还是没有运气.
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();
}
最后,我在编写此答案时放弃了传单,然后尝试Angular-Google-Maps.
Finally, I ditched leaflet while writing this answer, and I am going to try Angular-Google-Maps.
是的,A-G-M工作正常.
And yeah A-G-M is working fine.
这篇关于Angular 7:从订阅内部调用时,ChangeDetectorRef detectChanges()导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!