我已经声明了一个变量,现在尝试分配一个值,但它会抛出错误,它如何在tyoescript中工作,它是否在严格模式下工作并被提升。解决此问题的正确方法是什么?
此外,如果我在javascript中将项目推送到数组,它不会将元素添加到数组?
main.component.ts
export class SlaChartComponent implements OnInit {
constructor(private chartService: ChartService, private detailService: DetailService) { };
public barChartLabels:string[] = [];
ngOnInit(){
this.messageArray = [];
this.detailService.currentMessage2.subscribe(message2 => {
this.chartService.getChart().subscribe(chartObj => {
console.log('DataChart',chartObj);
chartObj.forEach(function(item){
this.barChartLabels = item.date;
})
});
})
}
错误
ERROR TypeError: Cannot set property 'barChartLabels' of undefined
答案 0 :(得分:0)
更改此
chartObj.forEach(function(item){
this.barChartLabels = item.date;
})
为此:
chartObj.forEach((item) => {
this.barChartLabels = item.date;
});