Angular2 NgFor only supports binding to Iterables, e.g. Arrays error

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

}

Then I bind this in my template as:

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

My actual answer from the 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"}]}]

It causes an 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 just would like to iterate over the coreGoals properties, as well as access them for children and their properties.

+6
source share
1 answer

Your mistake:

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

There is no object with a name in your answer data, so delete dataand it should work:

private extractData(res: Response) {
  let body = res.json();
  return body || { }; // here
}
+8
source

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


All Articles