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
相关产品推荐
相关产品推荐

