7

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.

Thinker
  • 5,326
  • 13
  • 61
  • 137

1 Answers1

9

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
}
AT82
  • 71,416
  • 24
  • 140
  • 167
  • Can you please also point out how can I access it's children like in images -> base64 so that I can see the image on UI? – Thinker Mar 31 '17 at 10:29
  • I figured it out :) – Thinker Mar 31 '17 at 10:35
  • Just about to answer, but you figured it out, great! :) Have a good day and happy coding! – AT82 Mar 31 '17 at 10:41
  • Thanks a lot! But I still ran into error = > `` is it a correct way in my loop? – Thinker Mar 31 '17 at 10:43
  • I didn't notice that your image was of base64. Yeah, that looks about right though. But you will run to an "unsafe" error right? You need to check other SO posts about that... maybe this can help? http://stackoverflow.com/questions/38812993/base64-to-image-angular-2 – AT82 Mar 31 '17 at 11:00