Angular2 NgFor仅支持绑定到Iterables,例如Arrays错误
发布时间:2020-12-17 10:19:27 所属栏目:安全 来源:网络整理
导读:我有一个模特: export class CoreGoalModel { constructor( public title: string,public image: string,){}} 我的服务: getGoals(): ObservableCoreGoalModel[] { let headers = new Headers({ 'Access-Control-Allow-Origin': '*' }); let options = new
我有一个模特:
export class CoreGoalModel { constructor( public title: string,public image: string,){} } 我的服务: 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 || { }; } 然后在我的组件中: ngOnInit() { this.homeService.getGoals() .subscribe( goals => this.coreGoals = goals,error => this.errorMessage = <any>error); } 然后我在我的模板中将其绑定为: <ul> <li *ngFor="let goal of coreGoals"> {{goal.title}} </li> </ul> 我从服务器的实际响应: [{"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/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUnFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgonKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIAnAhEBAxEB/8QAHAABAAIDAQEB"}]}] 这会引发我的错误无法找到’object’类型的不同支持对象'[object Object]’. NgFor仅支持绑定到诸如Arrays之类的Iterables. 我究竟做错了什么?我只想迭代coreGoals属性,并访问它的子项及其属性.
你的错误在这里:
private extractData(res: Response) { let body = res.json(); return body.data || { }; // error } 您的响应没有对象命名数据,因此删除数据它应该工作: private extractData(res: Response) { let body = res.json(); return body || { }; // here } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |