![](/img/trans.png)
[英]I receive this error “TypeError: Cannot read property 'pagination' of undefined”
[英]I don't know why I receive this message in angular: “ERROR TypeError: Cannot set property 'position' of undefined”
我在角度組件中有一個JSON數組,我想將其移至另一個數組。
類型聲明:
測量細節
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”數組的初始化有關。 但我不知道如何解決。
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;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.