gpt4 book ai didi

angular - 子组件中的 ExpressionChangedAfterItHasBeenCheckedError

转载 作者:太空狗 更新时间:2023-10-29 18:18:33 26 4
gpt4 key购买 nike

我有一个父组件,它每秒更新一次它的数组 myValue。在子组件中,我想创建一个图表,它使用这个数组作为数据,并在每次父组件更新时更新。

当我运行此应用程序时出现此错误:

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'hidden: true'. Current value: 'hidden: false'.

这是我的父组件:

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements AfterContentInit, OnDestroy {

private myValues: MyValue[];
private alive: boolean;

constructor(private valueService: ValueService) {
this.alive = true;
this.myValues = [];
}

ngAfterContentInit(): void {
TimerObservable.create(0, 1000)
.takeWhile(() => this.alive)
.subscribe(() => {
this.valueService.doSmth().subscribe(
value => {
this.myValues.push(value);
}
);
});
}
...

}

父模板如下所示:

<ul>
<li *ngFor="let value of myValues">
<p>{{value.name}}</p>
</li>
</ul>

<app-value-chart [chartData] = myValues></app-value-chart>

这是我的子组件:

@Component({
selector: 'app-value-chart',
templateUrl: './value-chart.component.html',
styleUrls: ['./value-chart.component.scss']
)}
export class ValueChartComponent implements AfterViewInit {
@Input() chartData: MyValue[];

chart: any;

ngAfterViewInit(): void {
this.createChart(); // creates chart with ChartJS
const tmp: number[] = [];
for (let i = 0; i < this.chartData.length; i++) {
tmp.push(this.chartData[i].x);
}
this.chart.data.datasets[0].data = tmp;
this.chart.update(0);
}
...
}

子模板:

  <canvas id="canvas" responsive>{{ chart }}</canvas>

我该如何解决我的问题?

我使用 Angular 6。

最佳答案

您可以在 this article 中找到关于该异常的详细解释。 .消除异常的一种技术是使用 ChangeDetectorRef.detectChanges 强制更改检测:

export class ValueChartComponent implements AfterViewInit {

constructor(private cd: ChangeDetectorRef) { }

ngAfterViewInit(): void {
...
this.cd.detectChanges();
}

...
}

另一种技术是使用 setTimeout 异步运行处理程序代码:

export class ValueChartComponent implements AfterViewInit {

ngAfterViewInit(): void {
setTimeout(() => {
...
});
}

...
}

关于angular - 子组件中的 ExpressionChangedAfterItHasBeenCheckedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50973032/

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