[英]I don't know why I receive this message in angular: “ERROR TypeError: Cannot set property 'position' of undefined”
I have an array of JSON in an angular component and I want to move it to another array. 我在角度组件中有一个JSON数组,我想将其移至另一个数组。
declaration of types : 类型声明:
MeasurementDetails : 测量细节
export interface MeasurementDetails {
_id: string;
measureTitle: string;
measureDescription: string;
measureSymbol: string;
}
and MeasureTypeElemetns : 和MeasureTypeElemetns:
export interface MeasureTypeElemetns {
title: string;
position: number;
description: string;
symbol: string;
}
I declared two arrays with initialization like this : 我用这样的初始化声明了两个数组:
mp: MeasurementDetails[] = [];
ELEMENT_DATA: MeasureTypeElemetns[] = [];
I requested an HTTP request and it responded me. 我请求了一个HTTP请求,它响应了我。 I called it in constructor of component class like this: 我在组件类的构造函数中这样称呼它:
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" function declared like this: 声明为“ 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;
});
}
}
But when I run, it shows a message : 但是当我运行时,它显示一条消息:
"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"
I think this is related to initialization of my 'ELEMENT_DATA' array. 我认为这与我的“ ELEMENT_DATA”数组的初始化有关。 but I don't know how to solve it. 但我不知道如何解决。
ELEMENT_DATA
is empty array so it returns undefined
element. ELEMENT_DATA
为空数组,因此它返回undefined
元素。
Just assign a empty object like this.ELEMENT_DATA[i] = {}
before access to its property. 只需分配一个像this.ELEMENT_DATA[i] = {}
的空对象,然后再访问其属性。
This code will work. 此代码将起作用。
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;
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.