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

使用接口JSON数据创建手风琴时无法访问children属性的问题

问题分析与解决方案

错误原因拆解

  • 数组访问逻辑错误:tileData是Tile[]类型(数组),数组本身没有children属性,必须通过索引(如tileData[0])或遍历数组,才能访问单个Tile对象的children。
  • 接口返回结构不匹配:后端返回的JSON外层包含data字段,而你的服务直接将返回值声明为Tile[],导致tileData实际赋值的是整个外层对象,而非内部的数组数据。
  • Tile接口定义错误:实际返回的children是数组,但你定义的children是单个对象类型,类型不匹配会导致TS校验报错。

修复步骤与代码修改

1. 修正Tile接口的children类型

将children改为数组类型,匹配后端返回结构:

export interface Tile {
  name: string;
  image: string;
  // 修正为数组类型
  children: { name: string; image: string; url: string }[];
}

2. 定义后端返回的顶层接口

新增接口匹配外层data字段结构:

export interface TileResponse {
  data: Tile[];
}

3. 修复服务文件的请求类型

更新showTile方法的返回类型,对应顶层接口:

showTile() {
  return this.http.get<TileResponse>('http://localhost:3000/data');
}

4. 修正组件中的数据赋值与访问

在订阅回调中先提取data字段,再正确访问数组元素的children:

tileData!: Tile[];
getTileData() {
  this.tileService.showTile().subscribe((response: TileResponse) => {
    this.tileData = response.data;
    
    // 示例:访问第一个Tile的第一个子项名称
    console.log('第一个子项名称:', this.tileData[0].children[0].name);
    
    // 遍历所有Tile及子项(手风琴组件渲染时常用)
    this.tileData.forEach(tile => {
      tile.children.forEach(child => {
        console.log('子项名称:', child.name);
      });
    });
  });
}

内容的提问来源于stack exchange,提问作者Syed Abdul Hannan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:45:42