【问题标题】:Angular-Highcharts: Cannot read property of 'Apartment' of undefined of an objectAngular-Highcharts:无法读取对象未定义的“公寓”属性
【发布时间】:2018-07-02 03:08:14
【问题描述】:

我在 Angular 中使用 Highcharts,我有两个对象。

对象一具有模拟数据,对象二具有通过 xmlHttpRequest 从云中提取的数据。当我在 Highcharts 中使用对象一时,我得到了预期的结果,但使用对象二我得到了

ERROR TypeError: 无法读取未定义的属性“Condo”

错误类型错误:无法读取未定义的属性“公寓”

根据 console.log,两个对象看起来应该是相同的。

对象一:

var secondChartData = {
   Condo: [120],
   Apartment: [302],
}
//console log: secondChartData {Condo: Array(1), Apartment: Array(1)}

对象二:

buildingTypeObj = {};
buildingType: any[] = [];
buildingSize: any[] = [];
constructor() {
  // other codes
  this.buildingType.push(...from Firebase...);
  this.buildingSize.push(...from Firebase...);
  for(var j = 0; j < this.buildingType.length; j++) {
    this.buildingTypeObj[this.buildingType[j]] = [this.buildingSize[j]];
  }
  //console log: secondChartData {Condo: Array(1), Apartment: Array(1)}
}

Highcharts:

ngAfterViewInit): void {
  // other codes
  function renderSecond(e) {
    var point = this;
    series: [{
      data: this.buildingTypeObj[point.name], // doesn't work
      //data: secondChartData[point.name], // works
    }]
  }
}

REST API 通过异步,因为这是系统设置:

static async getInfo() {
  // other codes
  const xmlHttp = new XMLHttpREquest();
  xmlHttp.open("GET", groupsEndpoint, false); // false for async
  // other codes
}

我不明白为什么对象二会返回错误。

错误会不会是异步引起的?

Here is my Fiddle to show the intended behaviors

【问题讨论】:

    标签: javascript angular highcharts


    【解决方案1】:

    由于您使用了 ES5 函数语法,因此 this 的上下文发生了变化。

    您不能再使用 this 访问组件内的 buildingTypeObj

    相反,在您的函数上方有一个 this 的引用。

    ngAfterViewInit() {
      // other codes
      const self = this;
      function renderSecond(e) {
        series: [{
          data: self.buildingTypeObj[this.name],
          data: secondChartData[this.name], 
        }]
      }
    }
    

    【讨论】:

    • 很高兴学习新东西。你的回答解决了我困扰三天的问题。你是救世主。非常感谢。
    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多