【发布时间】:2019-04-27 07:06:46
【问题描述】:
我在阅读了与变更检测和类似帖子相关的所有材料并且未能解决我的问题后发布在这里。
ChangeDetectorRef detectChanges() 从订阅内部调用时会导致无限循环。如果我不打电话给detectChanges,我会收到ExpressionChangedAfterCheck 错误。我真的不知道如何解决,为什么ExpressionChangedAfterCheck错误来了
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绑定时才会出现此问题。
【问题讨论】:
-
如果您删除
this.cdRef.detectChanges();之一,您会收到ExpressionChangedAfterCheck错误吗? -
@ArtyomAmiryan 是的,亲爱的,即使我将调用包含在 setTimeOut 中,我也会收到这个令人沮丧的错误。我人生中第一次想到 Angular 的替代方案。在每个新版本之后,我们都会有新的怪癖。
-
首先在循环中订阅是错误的,在您的
while循环中想象您订阅Observable的次数,每次迭代更新属性值的目的是什么@ 987654331@ 和loading内订阅? -
再看一次,它是一个用于清除旧数据的while循环
-
试试
markForCheck而不是detectChanges。
标签: angular rxjs angular7 angular-lifecycle-hooks