繁体   English   中英

无法读取 Angular 中未定义的属性“单位”

[英]Cannot read property 'units' of undefined in Angular

我是 Angular 的新手,正在尝试加载具有 static 值(在 a.ts 文件中定义的值)的下拉列表。 在尝试使用值加载数组时,收到错误消息:

无法读取未定义的属性“correlationDepthUnits”。

我在下面提供了整个代码:

我试过的:

常数.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"},
    ]
}

单位.ts

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

主页.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);
    });
  }

}

模板文件

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

请帮我解决这个问题。 谢谢。

尝试使用箭头 function 代替匿名 function:

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

这是因为箭头 function 没有它自己的 this。 使用封闭词法 scope 的 this 值。 箭头函数遵循正常的变量查找规则。 因此,在搜索当前 scope 中不存在的 this 时,箭头 function 最终从其封闭的 scope 中找到了 this。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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