Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 NgFor only supports binding to Iterables such as Arrays error

Tags:

angular

I have a model:

export class CoreGoalModel {
  constructor(

    public title: string,
    public image: string, 

    ){}
}

My service:

  getGoals(): Observable<CoreGoalModel[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.base_url + 'coregoal', options)
    .map(this.extractData)
    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

And then in my component:

ngOnInit() {

    this.homeService.getGoals()
    .subscribe(
                 goals => this.coreGoals = goals,
                 error =>  this.errorMessage = <any>error);

}

I then am binding this in my template as:

<ul>
    <li *ngFor="let goal of coreGoals">
        {{goal.title}}
    </li>
</ul>

My actual response from server:

[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]

This throws me error Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

What am I doing wrong? I simply would like to iterate over coreGoals properties and also access it's children and their properties.

like image 807
Thinker Avatar asked Mar 31 '17 10:03

Thinker


1 Answers

Your error is here:

private extractData(res: Response) {
  let body = res.json();
  return body.data || { }; // error
}

Your response has no object named data, so remove data and it should work:

private extractData(res: Response) {
  let body = res.json();
  return body || { }; // here
}
like image 88
AT82 Avatar answered Nov 03 '22 02:11

AT82