[英]Angular2 - TypeError: Cannot read property 'Id' of undefined in (Typescript)
[英]Typescript/Angular2 TypeError: Cannot read property of undefined
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);
我已經玩了好幾個小時了,無法弄清楚我做錯了什么,感謝任何幫助。
問題是this
改變回調函數。 您可以使用修復這個箭頭的功能 ,這將捕捉到正確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);
});
這可能很有用: TypeScript中的“this”是什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.