Angular 12.2.5中遍历嵌套JSON并提取指定字段
解决Angular 12嵌套JSON遍历问题(提取title、views、solutionId)
问题分析
你当前的代码存在几个关键问题:
- 使用
keyvalue管道遍历根对象后,错误地直接通过键名element['Sector: Public Sector[14]']取值,实际上element.value就是对应的数据数组 - 对
solutionDetails使用keyvalue管道完全多余,因为它是一个对象,直接访问属性即可,不需要遍历键值对 - 模板结构嵌套混乱,导致无法正确绑定目标字段
修正方案
1. 组件层数据预处理(可选但推荐)
在组件类中,先把API返回的JSON数据转换为便于模板遍历的数组,避免模板里硬编码键名:
// 假设API返回的数据存在this.apiResponse中 this.solutions = Object.values(this.apiResponse)[0]; // 直接取根对象的第一个值,也就是Public Sector的数组
2. 修正模板代码
直接遍历预处理后的数组,或者在模板里处理原始数据,正确绑定需要的字段:
<div> <!-- 方式1:用预处理后的solutions数组 --> <ion-card *ngFor="let item of solutions"> <ion-card-header style="background-image: url('');background-size: cover;min-height:10rem;max-height:10rem;"> <button class="button-insight"></button> <ion-card-title class="card-header-text">{{item.solutionDetails.title}}</ion-card-title> </ion-card-header> <ion-card-content class="card-content"> <p>浏览量:{{item.solutionDetails.views}}</p> <p>解决方案ID:{{item.solutionId}}</p> <hr class="hr"> </ion-card-content> </ion-card> <!-- 方式2:直接处理原始apiResponse(不推荐硬编码键名) --> <!-- <ion-card *ngFor="let item of apiResponse['Sector: Public Sector[14]']"> <ion-card-header style="background-image: url('');background-size: cover;min-height:10rem;max-height:10rem;"> <button class="button-insight"></button> <ion-card-title class="card-header-text">{{item.solutionDetails.title}}</ion-card-title> </ion-card-header> <ion-card-content class="card-content"> <p>浏览量:{{item.solutionDetails.views}}</p> <p>解决方案ID:{{item.solutionId}}</p> <hr class="hr"> </ion-card-content> </ion-card> --> </div>
关键说明
- 避免在模板中硬编码类似
Sector: Public Sector[14]的键名,后续API返回的键名变化会导致代码失效,推荐在组件层用Object.values()统一处理 - 直接通过
.访问嵌套对象的属性,比如item.solutionDetails.title,不需要额外的管道或遍历 - 如果API返回多个类似的Sector数组,可以用
*ngFor="let sector of Object.values(apiResponse)"遍历所有Sector,再嵌套遍历每个Sector下的解决方案
内容的提问来源于stack exchange,提问作者irfan shaikh
相关产品推荐
相关产品推荐

