NgFor error while passing array

I have a Category object (id, name), I get like this on 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"));

Category.ts object:

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

And I'm trying to put them as options in an autocomplete field like this:

<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>

But I get the following error

An error occurred while trying to split the "object object". Only arrays and iterations allowed

I tried using

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

But is he still throwing the same error, what am I doing wrong?

+4
source share
2 answers

Looking at the json you commented out, you need to iterate over categories.result. Change *ngForas follows:

  <md-option *ngFor="let category of categories.result">
      {{ category.name }}
  </md-option>
+1
source

console.log(this.categories), , , . , .

0

Source: https://habr.com/ru/post/1685041/


All Articles