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

Angular 4应用中如何展示嵌套JSON中的属性?

解决嵌套JSON属性展示问题

核心问题在于你的Cliente接口结构和API返回的JSON嵌套结构完全不匹配,导致模板无法识别嵌套的Configuracao这类属性。咱们一步步来修正:

1. 修正数据模型,匹配API返回结构

首先要创建对应嵌套结构的子接口,再调整根接口来包含这些嵌套对象:

// 先定义各嵌套结构的子接口
export interface Pagamento {
  numeroCartao: string;
  valor: string;
  nome: string;
  codigoSeguranca: string;
  quantidadeParcelas: number;
  validade: string;
}

export interface Configuracao {
  receberNovidades: boolean;
  aceitaTermos: boolean;
}

export interface Endereco {
  estado: string;
  cidade: string;
  numero: string;
  logradouro: string;
  cep: string;
}

export interface Atributos {
  masculino: boolean;
  Tamanho: {
    calcado: number;
    short: string;
    camiseta: string;
  };
}

export interface ClienteDetalhes {
  celular: string;
  nome: string;
  apelido: string;
  sobrenome: string;
  email: string;
}

// 根接口,完全匹配API返回的JSON结构
export interface Cliente {
  id: string;
  cpf: string;
  Pagamento: Pagamento;
  Configuracao: Configuracao;
  Endereco: Endereco;
  Atributos: Atributos;
  Cliente: ClienteDetalhes;
}

2. 更新Service的返回类型

确保你的ClientesService返回的Observable类型和新的Cliente接口匹配:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Cliente } from './cliente.model'; // 导入新的接口

@Injectable()
export class ClientesService {
  constructor(private http: Http){}

  clientes(): Observable<Cliente[]>{
    return this.http.get(`URL`)
      .map(response => response.json())
  }
}

3. 调整Component的类型声明

组件里的clientes属性类型保持和Service返回一致即可:

import { Component, OnInit, Input } from '@angular/core';
import { ClientesService } from './clientes.service';
import { Cliente } from './cliente.model';

export class ClientesComponent implements OnInit {
  @Input() clientes: Cliente[];

  constructor(private clientesService: ClientesService) { }

  ngOnInit() {
    this.clientesService.clientes()
      .subscribe(clientes => this.clientes = clientes)
  }
}

4. 在模板中访问嵌套属性

现在就可以通过点语法直接访问Configuracao里的属性了,比如:

<tr *ngFor="let cliente of clientes">
  <td>{{cliente.Cliente.nome}}</td> <!-- 访问嵌套的Cliente对象里的名称 -->
  <td>{{cliente.cpf}}</td> <!-- 根节点的cpf属性 -->
  <td>{{cliente.Configuracao.receberNovidades ? '接收推送' : '不接收推送'}}</td> <!-- 展示Configuracao里的receberNovidades -->
  <td>{{cliente.Configuracao.aceitaTermos ? '已同意条款' : '未同意条款'}}</td>
</tr>

注意API返回的属性名是首字母大写的(比如Configuracao),模板里要严格对应这个拼写,不然会找不到属性哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:05:14