Copy data from one value object to another in typescript: Type Error: Cannot read properties of undefined (reading substring)"

Copy data from one value object to another in typescript: Type Error: Cannot read properties of undefined (reading substring)"

在 angular 12(使用打字稿)应用程序中,文件“houseobject.ts”中有一个值对象定义为:

export class houseValue {
  houseCodeAndDesc: string;
  numberBedrooms: number;
}

houseValue 的 JSON 显示为: 房屋价值{ houseCodeAndDesc: "10005 - Brownstone 公寓" 卧室数:“8” }

不幸的是,houseCodeAndDesc 信息需要分解为房屋代码和房屋描述(因此 houseCode:10005,houseDesc:Brownstone 公寓)。

我在名为 houseobject2.ts 的文件中创建了一个新的值对象,如下所示:

export class houseValueBrokenUp{
 houseCode: string;
 houseDesc: string;
 numberBedrooms: number;
 }

我试图将数据从 houseValue 映射到 houseValueBrokenUp,如下所示:

export class houseTable {
 @Input() houseSummary: houseValue[];
 displayedColumns: string[] = ['houseCodeAndDesc', 'numberBedrooms'];
 houseDisplayList: houseValueBrokenUp[];
 houseDisplay: houseValueBrokenUp;
 houseDataSource: MatTableDataSource<any>;
 houseSplitDataSource: MatTableDataSource<houseDisplayList>;

@ViewChild(MatSort) sort: MatSort;

ngOnInIt() {
 if(this.houseSummary) {
    this.setInformation();
    this.houseDataSource = new MatTableDataSource(this.houseSummary);
   }
 }

 setInformation() {
 for (const value of this.houseSummary) {
  this.houseDisplay.houseCode = value.houseCodeAndDesc.substring(0,5);
  this.houseDisplay.houseDesc = value.houseCodeAndDesc.substring(6);
  this.houseDisplay.numberBedrooms = value.numberBedrooms;
  this.houseDisplayList.push(this.houseDisplay);
 }
 }
}

问题是当 setInformation() 运行时,浏览器的控制台给出错误 “类型错误:无法读取未定义的属性(读取子字符串)”。 我相信它在说setInformation() 中的值未定义,但是当我 console.log(value) 时,控制台显示 JSON 信息。将值从原始值对象推送到拆分房屋代码和描述的值对象的正确方法是什么?

原因是houseDisplay没有初始化,是undefined。所以,你可以这样初始化它:

houseDisplay: houseValueBrokenUp = {
  houseCode: '',
  houseDesc: '',
  numberBedrooms: 0
};

此外,houseSummary 未定义 onInit。请阅读更多 component lifecycle.

如果您想在您的内容可用时立即设置信息,您可以使用 getter 和 setter,如下所示:

private _houseSummary: houseValue[];
houseDataSource = new MatTableDataSource([]);

get houseSummary():houseValue[]{
  return this._houseSummary;
}

set houseSummary(houseSummary:houseValue[]){
  this._houseSummary = houseSummary;
  if(this._houseSummary) {
    this.setInformation();
    this.houseDataSource.data = this._houseSummary;
  }
}

我不确定这是否有效,因为我没有直接测试但是是的...如果出现错误...查看控制台并在线进行良好的错误研究。