tengo un modelo:
export class CoreGoalModel { constructor( public title: string, public image: string, ){} }mi servicio:
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 || { }; }Y luego en mi componente:
ngOnInit() { this.homeService.getGoals() .subscribe( goals => this.coreGoals = goals, error => this.errorMessage = <any>error); }Luego estoy vinculando esto en mi plantilla como:
<ul> <li *ngFor="let goal of coreGoals"> {{goal.title}} </li> </ul>Mi respuesta real del servidor:
[{"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"}]}] Esto me arroja un error Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
¿Qué estoy haciendo mal? Simplemente me gustaría iterar sobre las propiedades de coreGoals y también acceder a sus hijos y sus propiedades.
Tu error está aquí:
private extractData(res: Response) { let body = res.json(); return body.data || { }; // error } Su respuesta no tiene un objeto llamado data , así que elimine data y debería funcionar:
private extractData(res: Response) { let body = res.json(); return body || { }; // here }