Angular 17从嵌套对象取值并在网格展示的问题求助
问题分析
你遇到的核心问题是返回的JSON数据结构层级问题:响应数据外层仅包含一个mainObjeto键,其对应的值才是你需要的完整业务对象。当前代码直接遍历整个响应对象,因此只会输出mainObjeto这个键,而它的值是嵌套对象,直接打印就会显示[object Object]。
解决方案
步骤1:修正数据赋值逻辑
在TS代码中,直接提取mainObjeto对应的值赋值给列表变量,同时因为模板用*ngFor遍历列表,单个对象需要包装成数组才能正常循环:
ngOnInit(): void { this.service.getData() .subscribe( data => { // 提取实际业务数据并包装为数组 this.list = [data.mainObjeto]; }); }
步骤2:处理嵌套结构的显示
业务对象包含嵌套对象(如reclamoMotivo、empresa)和数组(adjuntos),以下两种方案可解决显示问题:
方案A:递归组件处理任意嵌套结构
适合需要动态遍历所有字段的场景,创建一个递归组件object-display:
- 组件HTML (
object-display.component.html)
<div *ngFor="let item of data | keyvalue"> <p> Key: <b>{{item.key}},</b> Value: <ng-container *ngIf="isObject(item.value)"> <app-object-display [data]="item.value"></app-object-display> </ng-container> <ng-container *ngIf="isArray(item.value)"> <div *ngFor="let arrItem of item.value"> <app-object-display [data]="arrItem"></app-object-display> </div> </ng-container> <ng-container *ngIf="!isObject(item.value) && !isArray(item.value)"> <b>{{item.value}}</b> </ng-container> </p> </div>
- 组件TS (
object-display.component.ts)
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-object-display', templateUrl: './object-display.component.html' }) export class ObjectDisplayComponent { @Input() data: any; isObject(value: any): boolean { return typeof value === 'object' && value !== null && !Array.isArray(value); } isArray(value: any): boolean { return Array.isArray(value); } }
- 主组件中使用
<div class="bank" *ngFor="let item of list"> <app-object-display [data]="item"></app-object-display> </div>
方案B:针对性展示指定字段(更适合网格场景)
如果是固定列的网格展示,直接绑定字段名更清晰直观:
<div class="bank" *ngFor="let item of list"> <p>ID: <b>{{item.id}}</b></p> <p>描述: <b>{{item.descripcion}}</b></p> <p>投诉原因: <b>{{item.reclamoMotivo.descripcion}}</b></p> <p>企业名称: <b>{{item.empresa.nombreEmpresa}}</b></p> <p>附件列表:</p> <ul> <li *ngFor="let adjunto of item.adjuntos">{{adjunto.nombreAdjunto}}</li> </ul> <p>创建时间: <b>{{item.fechaCreacion | date:'yyyy-MM-dd HH:mm'}}</b></p> <p>客户邮箱: <b>{{item.correoCliente}}</b></p> <p>投诉状态: <b>{{item.reclamoEstado.reclamoEstadoMaestro.descripcion}}</b></p> <p>支持备注: <b>{{item.reclamoEstado.commentSupport}}</b></p> </div>
内容的提问来源于stack exchange,提问作者Eduardo Andia Romero
相关产品推荐
相关产品推荐

