Angular使用*ngFor迭代JSON时报错NgFor仅支持可迭代对象如何解决
错误原因
你本地的employees.json返回的是外层包含status、data、message的包裹对象,员工数组仅存在于该对象的data字段中。你当前代码直接将整个外层对象当做数组赋值给emplist,*ngFor遍历非可迭代的对象时就会抛出该错误。
解决方案
方案1:修改服务层直接返回员工数组(推荐)
服务层统一封装数据处理逻辑,调整employee.service.ts的getEmployees方法,通过RxJS的map操作符提取响应中的data字段:
// gets the Employees from the file: getEmployees(): Observable<Employee2[]> { return this.http .get<{data: Employee2[]}>(this.url) // 修正响应类型为实际的外层包裹结构 .pipe( map(res => res.data), // 提取员工数组返回 catchError(this.handleError<Employee2[]>('getEmployees', [])) ); }
原代码中已导入map操作符,无需额外新增导入。
方案2:组件层接收时提取data字段
如果不需要修改服务逻辑,直接调整newemployee.component.ts的订阅逻辑即可:
ngOnInit(): void { this.employeeService.getEmployees().subscribe((data: any) => { this.emplist = data.data; // 从响应对象中提取员工数组赋值 }); }
可选优化
可以在模板的列表渲染外层加非空判断,避免初始化时emplist为undefined导致的潜在报错:
<tbody *ngIf="emplist"> <tr *ngFor="let employee of emplist"> <!-- 原有td内容保持不变 --> </tr> </tbody>
内容的提问来源于stack exchange,提问作者CuriousGeo66
相关产品推荐
相关产品推荐

