我在有角组件中有一个JSON数组,我想将其移动到另一个数组。
类型声明:
MeasurementDetails:
export interface MeasurementDetails {
_id: string;
measureTitle: string;
measureDescription: string;
measureSymbol: string;
}
和MeasureTypeElemetns:
export interface MeasureTypeElemetns {
title: string;
position: number;
description: string;
symbol: string;
}
我用这样的初始化声明了两个数组:
mp: MeasurementDetails[] = [];
ELEMENT_DATA: MeasureTypeElemetns[] = [];
我请求了HTTP请求,并且它响应了我。 我在组件类的构造函数中这样称呼它:
this.mpserv.getall().subscribe(
x => {
x.forEach(elementj => {
this.mp.push(elementj);
});
this.filltoelements(this.mp);
},
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
“ filltoelements”函数声明如下:
filltoelements(mdata: MeasurementDetails[]) {
if (!mdata) {
console.log('data is undefined!!!!');
} else {
let i = -1;
mdata.forEach(elementi => {
i++;
this.ELEMENT_DATA[i].position = (i + 1);
this.ELEMENT_DATA[i].title = elementi.measureTitle;
this.ELEMENT_DATA[i].description = elementi.measureDescription;
this.ELEMENT_DATA[i].symbol = elementi.measureSymbol;
});
}
}
但是当我跑步时,它会显示一条消息:
"ERROR TypeError: Cannot set property 'position' of undefined
at measure-type.component.ts:74
at Array.forEach (<anonymous>)
at MeasureTypeComponent.push../src/app/cc/measurement/measure-
type/measure-type.component.ts.MeasureTypeComponent.filltoelements"
我认为这与我的“ ELEMENT_DATA”数组的初始化有关。但我不知道如何解决。
答案 0 :(得分:2)
ELEMENT_DATA
是空数组,因此它返回undefined
元素。
在访问其属性之前,只需分配一个this.ELEMENT_DATA[i] = {}
之类的空对象即可。
此代码将起作用。
filltoelements(mdata: MeasurementDetails[]) {
if (!mdata) {
console.log('data is undefined!!!!');
} else {
let i = -1;
mdata.forEach(elementi => {
i++;
this.ELEMENT_DATA[i] = {} as MeasureTypeElemetns;
this.ELEMENT_DATA[i].position = (i + 1);
this.ELEMENT_DATA[i].title = elementi.measureTitle;
this.ELEMENT_DATA[i].description = elementi.measureDescription;
this.ELEMENT_DATA[i].symbol = elementi.measureSymbol;
});
}
}