在我之前有很多人,我有这个错误:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我尝试了许多解决方案,例如: error display in *ngfor json array object
但没有任何作用。
public getInterfaces(): Observable<InterfaceBrief[]> {
let headers = this.createBasicHeaders();
let options = new RequestOptions({
method: 'get',
headers: headers});
let url = this.restApi +"/dashboard/list";
console.log(url);
return this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log("GOOD");
return body.data || {};
}
export class DashboardComponent implements OnInit {
errorMessage: string;
interfacesBrief: InterfaceBrief[];
constructor(private _service: AuthService, private _emotService: EmotClientService) {
}
ngOnInit() {
this.getInterfaces();
}
getInterfaces() {
this._emotService.getInterfaces().subscribe(
data => this.interfacesBrief = data,
error => this.errorMessage = <any>error
);
}
}
当我改变时:
return body.data || {};
到:
return body.data.items || {};
我有错误:
Cannot read property 'items' of undefined
错误:无法读取属性&#39;数据&#39;未定义的
答案 0 :(得分:1)
根据评论,当您在console.log中回复时:Array[2] 0 : Object 1 Object client: "client1" countKO: 3 (...)
您的回复中显然没有data
个对象,因此您应该按原样返回回复。
private extractData(res: Response) {
let body = res.json();
return body || []; // here!
}
当您收到响应时,您只需迭代该数组并显示所需的属性,如下所示:
<div *ngFor='let item of interfacesBrief'>
{{item.client}} - {{item.countKO}}
<!-- print whatever else properties you have and want to display -->
</div>
答案 1 :(得分:0)
仅返回res.json()
(为什么有时候如果没有提取数据而不是角度会在这里抛出错误)。
尝试在HTML中使用elvis运算符(安全导航)。
试试此代码
private extractData(res: Response) {
let body = res.json();
console.log("GOOD");
return body || {};
}
export class DashboardComponent implements OnInit {
...............
getInterfaces() {
this._emotService.getInterfaces().subscribe(
data => {
this.interfacesBrief = data
console.log(this.interfacesBrief ,"Without Error")
},
error => this.errorMessage = <any>error
);
}
}
<div *ngFor='let items of interfacesBrief?.data?.items'>
{{items}}
</div>