4

I have the object Categories(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")); 

The object Categories.ts:

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

And I am trying to put them as options on 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

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

I tried with

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

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

3
  • Can you change .then(response => this.categories = response.json()) to .then(response => { this.categories = response.json(); console.log(%O, this.categories); }) and show us the output? Commented Sep 4, 2017 at 19:59
  • I am not sure if it's related to your issue, but your class properties are not correctly declared. put public id: string, public name: string outside of the constructor. Commented Sep 4, 2017 at 20:35
  • @Vega, there is nothing wrong with that declaration. That is absolutely correct code. Imagine injecting a service in constructor, but you are able to use that throughout the class. This is similar. Commented Sep 4, 2017 at 20:41

2 Answers 2

1

Looking at the json you commented, you need to iterate over categories.result. Change your *ngFor to following:

 <md-option *ngFor="let category of categories.result"> {{ category.name }} </md-option> 
Sign up to request clarification or add additional context in comments.

Comments

0

Add a console.log(this.categories) where you are getting your response and then see what's being assigned to categories. I am sure that you parsing it in wrong way.

4 Comments

You should write that as a comment or support your answer with an example.
Not enough rep for a comment I think
I got this: {"result":[{"id":1,"name":"Football"},{"id":2,"name":"Basketball"},{"id":3,"name":"Rugby"}],"id":175,"exception":null,"status":5,"isCanceled":false,"isCompleted":true,"creationOptions":0,"asyncState":null,"isFaulted":false}
Greate !! you then have to use this.categories.result to access your data instead of this.categories...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.