首页 文章

错误消息的解决方案“NgFor仅支持绑定到诸如Arrays之类的Iterables”不起作用

提问于
浏览
0

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

所以在我的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);
    });
  }

我收到以下错误消息:

错误:无法找到'object'类型的不同支持对象'[object Object]' . NgFor仅支持绑定到诸如Arrays之类的Iterables .

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

不过,我收到此错误消息,好像this.products实际上不是一个数组 .

这里发生了什么?

1 回答

  • 1

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

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

相关问题