gpt4 book ai didi

Angular 4 ExpressionChangedAfterItHasBeenCheckedError

转载 作者:太空狗 更新时间:2023-10-29 16:55:07 25 4
gpt4 key购买 nike

在父组件中 =>

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '[object Object]'.
at viewDebugError (vendor.bundle.js:8962)
at expressionChangedAfterItHasBeenCheckedError (vendor.bundle.js:8940)

父组件 Html

<div>
<app-child-widget [allItems]="allItems" (notify)="eventCalled($event)"></app-child-widget>
<div>

父组件

export class ParentComponent implements OnInit {

returnedItems: Array<any> = [];
allItems: Array<any> = [];

constructor(
) { }

ngOnInit() {
this.allItems = // load from server...
}

eventCalled(items: Array<any>): void {
this.returnedItems = items;
}
}

子组件

@Component({
selector: 'app-child-widget',
templateUrl: 'child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Output() notify: EventEmitter<any> = new EventEmitter();
@Input() private allItems: Array<any>;

constructor() { }

ngOnInit() {
doSomething();
}

doSomething() {
this.notify.emit(allItems);
}
}

最佳答案

文章 Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error 非常详细地解释了这种行为

原因

您的问题与 to this one 非常相似,但不是通过服务更新父属性,而是通过同步事件广播更新它。这是 linked answer 的引述:

During digest cycle Angular performs certain operations on child directives. One of such operations is updating inputs and calling ngOnInit lifecycle hook on child directives/components. What's important is that these operations are performed in strict order:

  • Update inputs
  • Call ngOnInit

因此,在您的情况下,Angular 更新了子组件上的输入绑定(bind) allItems,然后在子组件上调用了 onInit,这导致了对 allItems 的更新父组件。现在你有数据不一致。父组件有一个值,而子组件有另一个值。如果 Angular 继续同步更改,您将陷入无限循环。这就是为什么在下一个更改检测周期中,Angular 检测到 allItems 已更改并抛出错误。

解决方案

这似乎是一个应用程序设计缺陷,因为您正在从父组件和子组件更新 details。如果不是,那么您可以像这样异步发出事件来解决问题:

export class ChildComponent implements OnInit {
@Output() notify: EventEmitter<any> = new EventEmitter(true);
^^^^^^-------------

但是你必须非常小心。如果您使用在每个摘要周期调用的任何其他 Hook ,例如 ngAfterViewChecked您最终将陷入循环依赖!

关于Angular 4 ExpressionChangedAfterItHasBeenCheckedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44691745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com