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

Angular向嵌套数组插入对象报错:Cannot read properties of undefined

错误原因分析
  • mockData 是一个空数组 [],组件内的 templates 初始值同步为空数组。调用 add() 方法时,this.templates[0] 为 undefined,无法读取不存在的对象的 subCategory 属性,因此抛出 TypeError: Cannot read properties of undefined (reading 'subCategory')。
  • 额外提醒:即便 templates 中有元素,若未初始化 subCategory 为空数组,后续调用 push 时同样会因 subCategory 是 undefined 报错。
解决方法

方法一:提前初始化主分类数据

修改 mockData,添加符合 ITemplate 接口的对象,并确保 subCategory 初始化为空数组:

const mockData: ITemplate[] = [
  {
    id: 1,
    entitlement: "示例主分类",
    required: false,
    isHeaderCategory: true,
    subCategory: [] // 必须初始化空数组,避免subCategory为undefined
  }
];

此时调用 add() 方法,this.templates[0] 存在且 subCategory 是合法数组,可正常执行 push 操作。

方法二:动态创建主分类后再添加子项

如果需要先创建主分类再添加子分类,可新增方法并修改 add() 逻辑:

// 新增:添加主分类的方法
addMainCategory() {
  const newCategory: ITemplate = {
    id: Date.now(),
    entitlement: "新主分类",
    required: false,
    isHeaderCategory: false,
    subCategory: []
  };
  this.templates.push(newCategory);
}

// 修改add()方法,确保操作的主分类存在
add() {
  // 无主分类时先创建
  if (this.templates.length === 0) {
    this.addMainCategory();
  }
  // 向第一个主分类的subCategory添加子项
  this.templates[0].subCategory.push({
    id: Date.now(),
    sub_name: 'test'
  });
}

关键注意点

所有 ITemplate 类型的对象,必须显式初始化 subCategory 为空数组,否则即便通过 TypeScript 编译,运行时也会因 subCategory 为 undefined 导致 push 失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:15:24