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

Angular12 TypeScript值对象映射报substring未定义错误如何解决

问题根因

映射报错和功能异常有以下几个核心原因:

  • 未初始化houseDisplayList数组,直接调用push()方法会抛出 undefined 相关错误
  • 每次循环未新建houseValueBrokenUp实例,直接给未初始化的全局houseDisplay属性赋值,会导致首次赋值就触发undefined报错,且后续所有元素都会引用同一个对象
  • 硬编码截取字符串长度的拆分方式容错性极低,同时接口返回的numberBedrooms是字符串类型,和定义的数值类型不匹配
  • 生命周期钩子拼写错误,ngOnInIt应为ngOnInit,拼写错误会导致钩子逻辑完全不触发
  • houseSplitDataSource的泛型定义错误,应该传入单个元素的类型houseValueBrokenUp,而不是数组类型

正确实现代码

可选优化:给拆分后的值对象增加构造函数(方便实例化)

// houseobject2.ts
export class houseValueBrokenUp{
  houseCode: string;
  houseDesc: string;
  numberBedrooms: number;
  // 新增构造函数
  constructor(code: string, desc: string, bedrooms: number) {
    this.houseCode = code;
    this.houseDesc = desc;
    this.numberBedrooms = bedrooms;
  }
}

修正组件逻辑

// 组件类需实现OnInit接口
export class houseTable implements OnInit {
  @Input() houseSummary: houseValue[];
  // 拆分后调整显示列
  displayedColumns: string[] = ['houseCode', 'houseDesc', 'numberBedrooms'];
  // 初始化数组
  houseDisplayList: houseValueBrokenUp[] = [];
  houseDataSource: MatTableDataSource<houseValue>;
  // 修正泛型类型
  houseSplitDataSource: MatTableDataSource<houseValueBrokenUp>;

  @ViewChild(MatSort) sort: MatSort;

  // 修正生命周期钩子拼写
  ngOnInit() {
    if(this.houseSummary?.length) {
      this.setInformation();
      this.houseDataSource = new MatTableDataSource(this.houseSummary);
      // 赋值拆分后的数据源
      this.houseSplitDataSource = new MatTableDataSource(this.houseDisplayList);
      this.houseSplitDataSource.sort = this.sort;
    }
  }

  setInformation() {
    // 清空数组避免重复追加
    this.houseDisplayList = [];
    for (const value of this.houseSummary) {
      // 按分隔符拆分字段,容错空值
      const [codePart, descPart] = value.houseCodeAndDesc?.split(' - ') || ['', ''];
      // 每次循环新建实例,转换numberBedrooms类型
      const houseItem = new houseValueBrokenUp(
        codePart,
        descPart,
        parseInt(value.numberBedrooms as unknown as string, 10) || 0
      );
      this.houseDisplayList.push(houseItem);
    }
  }
}

如果你不想给值对象新增构造函数,也可以直接用符合类型定义的对象字面量赋值:

const houseItem: houseValueBrokenUp = {
  houseCode: codePart,
  houseDesc: descPart,
  numberBedrooms: parseInt(value.numberBedrooms as unknown as string, 10) || 0
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:27:03