gpt4 book ai didi

angular - ExpressionChangedAfterItHasBeenCheckedError : by iterating a map

转载 作者:行者123 更新时间:2023-12-04 00:23:55 31 4
gpt4 key购买 nike

我有一个简单的 Angular 组件,在渲染时抛出以下错误:

MyComponent.html:10 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngForOf: [object Map Iterator]'.
Current value: 'ngForOf: [object Map Iterator]'.

错误被抛出两次,即使移动到没有其他代码的最低限度的 Angular 项目(只是一个包装此组件的 AppComponent)也是如此。

我将代码最小化为仍然重现问题的最小形式。我用硬编码的可观察对象替换了数据服务。

组件

@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss'],
})
export class MyComponent implements OnInit, OnDestroy {

private cobs: Map<number, string>;
private cobSub: Subscription;

constructor() {}

ngOnInit() {
// originally data comes from a service...
this.cobSub = of(new Map<number, string>([[1, 'a'], [2, 'b']]))
.subscribe({
next: cobs => { this.cobs = cobs; },
});
}

ngOnDestroy(): void {
this.cobSub.unsubscribe();
}

}

请注意,asyncPipe 更常用于此类场景 - 但我不能使用它。

模板

<div>
<table *ngIf="cobs">
<tr>
<th>Id</th>
<th>Class of Business</th>
</tr>
<tr *ngFor="let key of cobs.keys()">
<td>{{key}}</td>
<td>{{cobs.get(key)}}</td>
</tr>
</table>
</div>

为什么会出现这个问题?

如何修复?

最佳答案

你在Map上迭代的方式有问题,你可以试试:

export class AppComponent implements OnInit {
private cobs = new Map<number, string>();
private cobSub: Subscription;

constructor() {}

ngOnInit() {
this.cobSub = of(new Map<number, string>([[1, 'a'], [2, 'b']]))
.subscribe( cobs => {
this.cobs = cobs;
});
}

getKeys(map){
return Array.from(map.keys()); // add it
}
ngOnDestroy(): void {
this.cobSub.unsubscribe();
}
}

在 html 中:

<div>
<table *ngIf="cobs">
<tr>
<th>Id</th>
<th>Class of Business</th>
</tr>
<tr *ngFor="let key of getKeys(cobs)">
<td>{{key}}</td>
<td>{{cobs.get(key)}}</td>
</tr>
</table>
</div>

demo

如果您使用的是 Angular 6.1+,则可以使用默认管道 keyvalue :

<tr *ngFor="let key of cobs | keyvalue">
<td>{{key.key}}</td>
<td>{{key.value}}</td>
</tr>

关于angular - ExpressionChangedAfterItHasBeenCheckedError : by iterating a map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471841/

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