错误消息"NgFor only supports binding to Iterables such as Arrays"不起作用的解决方案



在我的角度应用程序中,我想显示用户可以选择的产品列表。

所以在我的 html 文件中,我编写了以下代码:

<section fxLayout="column" fxLayoutAlign="center center">
<mat-selection-list #products>
<mat-list-option *ngFor="let product of products">
{{product.name}}
</mat-list-option>
</mat-selection-list>
</section>

在 .ts 文件中,我有以下代码:

products;

constructor(private productService: ProductService) { }
ngOnInit() {
this.loadAll();
}

private loadAll(): Promise<any> {
this.products = [];
return this.productService.getAll()
.toPromise()
.then((result) => {
result.forEach(product => {
this.products.push(product);
});
})
.catch((error) => {     
console.log(error);
});
}

我收到以下错误消息:

错误:找不到类型为"对象"的不同支持对象"[对象对象]"。NgFor 仅支持绑定到可迭代对象(如数组(。

问题是:产品是一个数组(!(。

尽管如此,我还是收到此错误消息,就好像 this.products 实际上不是一个数组一样。

这是怎么回事?

你已经有一个数组,所以不需要再次转换为数组,

result.forEach(product => {
this.products.push(product);
});
this.products = Array.of(this.products); //remove this line

相关内容

最新更新