You need to enable JavaScript to run this app. Angular报错Error trying to diff '[object Object]' 读取JSON数据渲染失败
优惠活动
大模型
产品
解决方案
定价
更多

Angular报错Error trying to diff '[object Object]' 读取JSON数据渲染失败

问题原因

报错Error trying to diff '[object Object]'. Only arrays and iterables are allowed是因为Angular的*ngFor指令仅支持遍历数组或可迭代类型数据。你当前直接把接口返回的完整JSON对象赋值给了声明为数组类型的postArray,导致*ngFor遍历的目标实际是对象而非数组,触发类型不匹配错误。
从你给出的JSON结构可以看到,你需要的国家数组是存储在返回对象的flags字段里的,直接取整个返回对象赋值不符合要求。

解决方案

修改ts文件中getAllNations方法里的赋值逻辑,从返回结果中取出flags字段赋值给postArray即可:

getAllNations() {
  this.homeService.getAll().subscribe((result: {flags: Ipost[]}) => {
    // 提取flags字段的数组赋值
    this.postArray = result.flags;
    console.log(this.postArray);
  });
}
额外优化建议
  • 给homeService.getAll()方法添加返回值泛型约束,提前明确返回数据结构,避免后续出现类似的类型错误
  • 可以在模板中添加数组非空判断,避免数据未加载完成时出现异常:
<ng-container *ngIf="postArray.length">
  <div class="col-1 px-0" *ngFor="let post of postArray">
    <div *ngIf="post.id >= 13">
      <span>{{post.libelle}}</span>
    </div>
  </div>
</ng-container>

内容的提问来源于stack exchange,提问作者user16356529

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 20:09:02