简体   繁体   中英

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.

declaration of types :

MeasurementDetails :

export interface MeasurementDetails {
  _id: string;
  measureTitle: string;
  measureDescription: string;
  measureSymbol: string;
}

and 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. 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(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. but I don't know how to solve it.

ELEMENT_DATA is empty array so it returns undefined element.

Just assign a empty object like this.ELEMENT_DATA[i] = {} before access to its property.

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;
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM