html – 传递数组时的抛出错误

我有对象Categories(id,name),我在Angular上得到这样的:

this.categories = new Array<Category>();

this.http
    .get(ApiConfig.API_URL + 'getCategories')
    .toPromise()
    .then(response => this.categories = response.json())
    .catch(_ => console.log("error getting categories"));

对象Categories.ts:

export class Category
{
    constructor(
        public id: string,
        public name: string)
    { }
}

我试图将它们作为选项放在自动完成字段上,如下所示:

<div>
  <md-form-field>
    <input type="text" mdInput [mdAutocomplete]="auto">
  </md-form-field>
  <md-autocomplete #auto="mdAutocomplete">
    <md-option *ngFor="let category of categories">
      {{ category.name }}
    </md-option>
  </md-autocomplete>
</div>

但是我收到以下错误

Error trying to diff ‘[object Object]’. Only arrays and iterables are allowed

我试过了

<md-option *ngFor="let category of categories" [value]="category.id" [label]="category.name">

但它仍然抛出同样的错误,我做错了什么?

最佳答案 看看你评论过的json,你需要遍历categories.result.将您的* ngFor更改为以下内容:

  <md-option *ngFor="let category of categories.result">
      {{ category.name }}
  </md-option>
点赞