Angular 错误消息“NgFor仅支持绑定到Iterables(如数组)”的解决方案不起作用
在我的angular应用程序中,我想显示用户可以选择的产品列表 因此,在我的html文件中,我编写了以下代码:Angular 错误消息“NgFor仅支持绑定到Iterables(如数组)”的解决方案不起作用,angular,ngfor,Angular,Ngfor,在我的angular应用程序中,我想显示用户可以选择的产品列表 因此,在我的html文件中,我编写了以下代码: <section fxLayout="column" fxLayoutAlign="center center"> <mat-selection-list #products> <mat-list-option *ngFor="let product of products"> {{product.
<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>
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);
});
}
在.ts文件中,我有以下代码:
<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>
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);
});
}
我收到以下错误消息:
错误:找不到类型为“object”的不同支持对象“[object]”。NgFor只支持绑定到数组之类的可重用文件
问题是:产品就是!数组
尽管如此,我还是收到了这个错误消息,好像this.products实际上不是一个数组
这是怎么回事?您已经有了一个数组,因此无需再次转换为数组
result.forEach(product => {
this.products.push(product);
});
this.products = Array.of(this.products); //remove this line
我也这么想。。。我添加这行只是为了确保我得到了一个数组。。。我以前没有包括这一行。。。。希望通过这种方式消除错误。。。。但错误仍然完全相同:NgFor只支持绑定到Iterables,如Arrayscan,您可以发布console.logJSON.stirngifithis.products的结果;[{$class:org.comp.app.Product,company:Nike,logItems:[],id:2,name:test}]我删除了你告诉我的那行代码。。。上面的输出是删除this.products=Array.ofthis.products;…行后得到的输出。。。。我一直收到相同的错误消息,告诉我ngFor只能用于arraysmay-be-for-cache@Tommy