html - ngFor 在传递数组时抛出错误

标签 html angular typescript

我有对象 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>

关于html - ngFor 在传递数组时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043337/

相关文章:

html - CSS float 左问题

typescript - Webstorm、TypeScript、Angular2、Transpiler、重复标识符错误消息

javascript - 范围内可观察的随机数序列

javascript - 响应显示/隐藏菜单故障

html - 光标不会激活以允许在文本框中输入

Angular 8 - SimpleChange 类中的 firstChange 与 isFirstChange()

Angular2 使用组件外部的动画

typescript - 使用 AMD 时如何在 typescript 中定义和使用枚举?

jquery - 具有较大可点击区域的 HTML 表单

等待点击 Promise 完成的 Angular 指令