【问题标题】:Typescript/Angular2 TypeError: Cannot read property of undefinedTypescript/Angular2 TypeError:无法读取未定义的属性
【发布时间】:2017-04-07 04:19:23
【问题描述】:

Ang2 组件:

import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import Chart from 'chart.js'

@Component({
  selector: 'app-prchart',
  templateUrl: './app-prchart.component.html',
  styleUrls: ['./app-prchart.component.css']
})
export class AppPRChartComponent implements OnInit {
  userEmail: any;
  email: string;
  uid: any;
  records = [];
  newRecords = [];
  filteredRecords = [];
  labels = [];

  public barChartOptions:any = {
    scaleShowVerticalLines: false,
    responsive: true,
    legend: {
        display: false
     }
  };
  public barChartColors: any [] =[
    {
        backgroundColor:'rgba(30, 136, 229, 1)'
    }
  ];

  public barChartType:string = 'bar';

  constructor(public af: AngularFire) {
    var auth = this.af.auth.subscribe( (user) => {
      if (user) {


        this.userEmail = this.af.auth.subscribe(auth => {
          const queryObservable = af.database.list('/users/'+ auth.auth.uid +'/records/', {
          });
          queryObservable.subscribe(queriedItems => {
            this.records.push(queriedItems);
          });

          // Filter records into PR's
          this.newRecords =
          this.records[0].sort((a, b) => {
            if (a.movement === b.movement) {
              return a.weight >= b.weight ? -1 : 1
            }
            return a.movement > b.movement ? 1 : -1
          })
          .filter((rec, i, arr) => {
            if (i === 0) return true
            return rec.movement !== arr[i - 1].movement
          });
          let recordString = JSON.stringify(this.newRecords);
          let recordParse = JSON.parse(recordString);
          this.filteredRecords.push(recordParse);
        });
      } else {
      }
    });

    this.filteredRecords[0].forEach(function(snapshot) {
        this.labels.push(snapshot.movement);
        //barChartData.push(snapshot.weight);
    });
    //console.log(barChartLabels);
    //console.log(barChartData);
  }

  ngOnInit() {

  }

}

我正在尝试将项目推送到数组中,但我不断收到以下错误:

TypeError: Cannot read property 'labels' of undefined

错误发生在运行这行代码的底部:

this.labels.push(snapshot.movement);

我已经玩了几个小时了,无法弄清楚我做错了什么,感谢任何帮助。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    问题在于this 在回调函数内部发生了变化。您可以使用arrow functions 来解决此问题,这将捕获正确的this

    this.filteredRecords[0].forEach((snapshot) => {
        this.labels.push(snapshot.movement);
        //barChartData.push(snapshot.weight);
    });
    

    或者通过在另一个变量中捕获this

    let that = this;
    this.filteredRecords[0].forEach(function (snapshot) {
        that.labels.push(snapshot.movement);
        //barChartData.push(snapshot.weight);
    });
    

    这可能有用:What is 'this' in TypeScript

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2017-11-02
      • 2017-05-05
      • 1970-01-01
      相关资源
      最近更新 更多