返回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())
}
}
在此组件类中,我无法转换json数据,请任何人帮助我解决我的问题
export class EmployeeListComponent implements OnInit {
Employees:IEmployee[];
constructor( private _EmployeeService: EmployeeServiceService) {
}
ngOnInit() {
this._EmployeeService
.GetEmployees().subscribe((employeeData)=> this.Employees = employeeData);
}
}
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>
在此处输入代码
答案 0 :(得分:0)
每当您尝试将对象与ngFor绑定时,都会发生此错误。 ngFor指令仅支持数组。
按照请求,似乎它只返回一个对象,
return this._http.get("http://localhost:2724/api/employee/1")
如果仅需要绑定一个对象,则无需使用 ngFor
。
此外,您需要使用空数组初始化员工。
Employees:IEmployee[] = [];
如果您仍想将一个Object绑定到表,请按以下步骤将Object推入数组,
this.Employees.push(employeeData);
两个选项
(i)更改要求退还所有员工的请求
return this._http.get("http://localhost:2724/api/employee/all")
(ii)如下将对象推入数组,
ngOnInit() {
this._EmployeeService
.GetEmployees().subscribe((employeeData)=> this.Employees.push(employeeData);
}