为什么我的服务回调函数中没有可用的组件属性?

时间:2018-02-05 19:30:08

标签: javascript angular typescript

我已经声明了一个变量,现在尝试分配一个值,但它会抛出错误,它如何在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

1 个答案:

答案 0 :(得分:0)

更改此

chartObj.forEach(function(item){
    this.barChartLabels = item.date;
})

为此:

chartObj.forEach((item) => {
    this.barChartLabels = item.date;
});