[英]error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays how to solve
Service code which return json data 返回JSON数据的服务代码
export class EmployeeServiceService {
constructor(private _http:Http) { }
GetEmployees() :Observable<IEmployee[]>{
debugger;
return this._http.get("http://localhost:2724/api/employee/1")
.map((response:Response)=> <IEmployee[]>response.json())
}
}
In this component class im not able to convert the json data please any one help me to solve my issue 在此组件类中,我无法转换json数据,请任何人帮助我解决我的问题
export class EmployeeListComponent implements OnInit {
Employees:IEmployee[];
constructor( private _EmployeeService: EmployeeServiceService) {
}
ngOnInit() {
this._EmployeeService
.GetEmployees().subscribe((employeeData)=> this.Employees = employeeData);
}
}
html html
<tbody>
<tr *ngFor="let employee of Employees">
<td>{{employee.Address}}</td>
<td>{{employee.City}}</td>
<td>{{employee.EmployeeID}}</td>
<td>{{employee.FirstName}}</td>
<td>{{employee.LastName}}</td>
</tr>
<tr *ngIf="!Employees|| Employees.length== 0">
<td>No employee to display!!!</td>
</tr>
</tbody>
enter code here 在这里输入代码
This error occurs whenever you are trying to bind an Object with ngFor. 每当您尝试将对象与ngFor绑定时,都会发生此错误。 ngFor directive supports only arrays.
ngFor指令仅支持数组。
As per the request, it seems it returns only one Object, 根据请求,似乎它只返回一个Object,
return this._http.get("http://localhost:2724/api/employee/1")
if you need to bind only one Object no need to use ngFor
. 如果只需要绑定一个对象,则无需使用
ngFor
。
Also you need to initialize employees with an empty array. 另外,您需要使用空数组初始化员工。
Employees:IEmployee[] = [];
if you still want to bind one Object to the table, push the Object to the array as follows, 如果您仍然想将一个Object绑定到表,请按如下所示将Object推入数组,
this.Employees.push(employeeData);
Two options 两种选择
(i) Change your request to return all employees (i)更改您的要求返回所有员工的请求
return this._http.get("http://localhost:2724/api/employee/all")
(ii) Push the Object to an array as follows, (ii)按以下方式将对象推入数组,
ngOnInit() {
this._EmployeeService
.GetEmployees().subscribe((employeeData)=> this.Employees.push(employeeData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.