javascript - ngIf 中的 ExpressionChangedAfterItHasBeenCheckedError?
问题描述
我无法弄清楚我在这里缺少什么。
共享服务A:
export class SharedServiceA {
somethingWasUpdated = new Subject();
updateSomething(value) {
this.somethingWasUpdated.next(value);
}
}
另一个服务:
export class AnotherService {
doSomething() {
this.sharedServiceA.updateSomething(true);
}
}
组件-a.component.ts
export class ComponentA {
list = [];
isShowList = false;
ngOnInit() {
this.sharedServiceA.somethingWasUpdated
.pipe(takeUntil(this.destroyed))
.subscribe(
data => {
if (data) {
this.fetchData(); // Get data from another service, then populate list
}
}
);
}
fetchData() {
// Get data from another service
if (dataFound) {
this.list = dataFound;
this.isShowList = true;
} else {
this.isShowList = false;
}
}
}
组件-a.component.html
<div *ngIf="!isShowList"> <!-- This is where ExpressionChangedAfterItHasBeenCheckedError points to: Previous value: 'ngIf: true'. Current value: 'ngIf: false' -->
List empty
</div>
<div *ngIf="isShowList">
Print something here
</div>
组件-b.component.html
export class ComponentB {
ngOnInit() {
this.sharedServiceA.somethingWasUpdated
.pipe(takeUntil(this.destroyed))
.subscribe(
data => {
if (data) {
// Get data from another service
}
}
);
this.anotherService.doSomething(); // If I place this inside a setTimeout, I don't get the ExpressionChangedAfterItHasBeenCheckedError
}
}
这是场景:
单击一个按钮 >
ComponentA
在选项卡内创建单击另一个按钮 >
ComponentB
在另一个选项卡中创建(基本上与 并排ComponentA
)>ComponentA.fetchData()
>ExpressionChangedAfterItHasBeenCheckedError
为什么我会在被填充并设置为之后得到一个ExpressionChangedAfterItHasBeenCheckedError
in ,如果我放在a中,为什么我不会收到错误消息?ComponentA
list
isShowList
true
this.anotherService.doSomething();
setTimeout
此代码如何违反单向数据流?即使在阅读了几篇文章之后,我仍然对这种特殊情况感到困惑。
解决方案
快速点,ExpressionChangedAfterItHasBeenChecked 错误仅在开发模式下可见。不要在生产模式下显示。
推荐阅读
- mongodb - Customize existing document and add new fields in mongo aggregation
- javascript - 需要验证出生日期用户应该是 18 岁及以上
- c# - 不动态更新系统托盘通知图标?
- python - 如何将.condarc中提供的代理用于environment.yml中的pip包?
- python - GMM 函数的 GaussianMixture 等效项(sklearn python)
- javascript - React-hot-loader 不适用于 React-router-dom
- xml - 如何在报告中打印页码
- javascript - 克隆具有相同外观的屏幕外元素
- javascript - Vue.js 导入图片
- delphi - 与 SSL DLL 相关的问题