简体   繁体   中英

Cannot read property 'units' of undefined in Angular

Am new into Angular and am trying to load a dropdown with static values (values defined in a.ts file). While am trying to load the array with the values, am getting error message as:

Cannot read property 'correlationDepthUnits' of undefined.

Am providing the whole code below:

What I have tried:

Constant.ts

export class Constant {
public static Units = [
        {unit_name : "ft", unit_value : "ft", unit_description : "Feet"},
        {unit_name : "m", unit_value : "m", unit_description : "Meters"},
        {unit_name : "km", unit_value : "km", unit_description : "Kilometers"},
        {unit_name : "yd", unit_value : "yd", unit_description : "Yards"},
        {unit_name : "mi", unit_value : "mi", unit_description : "Miles"},
    ]
}

units.ts

export class units{
    unit_name : string;
    unit_value : string;
    unit_description : string;
}

main-page.Component.ts

import { Component, OnInit } from '@angular/core';
import { units } from '../../models/units';
import { Constant } from '../../Constant';

@Component({
  selector: 'app-well-data',
  templateUrl: './well-data.component.html',
  styleUrls: ['./well-data.component.css']
})
export class WellDataComponent implements OnInit {
  Units : units[] = [];

  constructor() {}

  ngOnInit(): void {
    this.getUnits();
  }

  getUnits() {
    debugger;
    /*
    for (var index = 0; index < Constant.Units.length; index++)
    {
      this.Units[index].unit_name = Constant.Units[index].unit_name;
      this.Units[index].unit_value = Constant.Units[index].unit_value;
      this.Units[index].unit_description = Constant.Units[index].unit_description;
    }
    */

    Constant.Units.forEach(function(item){
      this.Units.push(item);
    });
  }

}

Template file

<select class="form-control input-types fonts" id="corrDepth">
     <option *ngFor="let unit of correlationDepthUnits" 
              [value]="unit.unit_value">{{unit.unit_name}}
     </option>>
</select>

Please help me through this. Thanks.

Try to use arrow function instead anonymous function:

Constant.Units.forEach((item) => {
  this.Units.push(item);
});

This is because an arrow function does not have its own this. The this value of the enclosing lexical scope is used. Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in the current scope, an arrow function ends up finding the this from its enclosing scope.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

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