You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中*ngFor无法遍历数组数据的修复咨询

解决Angular *ngFor无法遍历嵌套数组的问题

问题根源

你当前的代码存在两个核心问题:

  1. 将API返回的单个对象包装进数组allData,导致*ngFor仅能执行1次遍历
  2. 模板中硬编码city[1].section[2]索引,只能获取固定位置的单条数据

组件代码优化

无需把API响应对象包装进数组,直接保存完整响应即可:

export class LiveComponent implements OnInit {
  apiData: any = null;
  constructor(private http: HttpClient ) {}

  ngOnInit(){
    this.http.get('http://api.redacted_for_privacy').subscribe(data => {
      this.apiData = data;
    });
  }
}

模板修改(遍历所有城市的所有街道)

使用嵌套*ngFor遍历city数组和每个city下的section数组,用ng-container避免生成冗余DOM元素:

<mat-list role="list">
  <!-- 遍历所有city -->
  <ng-container *ngFor="let city of apiData?.city">
    <!-- 遍历当前city下的所有section -->
    <mat-list-item role="listitem" *ngFor="let section of city.section">
      {{section.street}}
    </mat-list-item>
  </ng-container>
</mat-list>

可选:仅遍历指定城市的街道

如果只需要某个特定索引的city(比如第一个),可以简化模板:

<mat-list role="list">
  <mat-list-item role="listitem" *ngFor="let section of apiData?.city[0].section">
    {{section.street}}
  </mat-list-item>
</mat-list>

关键说明

  • 使用?.可选链操作符,避免API数据未加载完成时出现null/undefined报错
  • 嵌套*ngFor可以逐层遍历API返回的嵌套数组结构,完整展示所有街道数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:52:29