尝试推送数据时未定义数组的角度2抛出错误

时间:2019-01-08 13:40:06

标签: angular typescript

我正在Angular2组件中工作,在该组件中我声明了字符串数组并同时进行了初始化,在该组件中,我试图通过一种方法尝试推送数据,但得到未定义的错误,不确定我在这里缺少什么! / p>

export class MyComponent implements OnInit {

    public categoryData: string[] = [];

    ngOnInit(): void {

    }

    public loadDataFromServer() {

        let MyServerData = result.data;

        MyServerData.forEach(function (item) {
            this.categoryData.push(item.BarTitle); // error here
        });
    }
}

错误

ERROR TypeError: Cannot read property 'categoryData' of undefined

2 个答案:

答案 0 :(得分:4)

您必须使用箭头函数,否则您将this上下文丢失到使用function关键字创建的新匿名函数中:

MyServerData.forEach((item) => {
  this.categoryData.push(item.BarTitle); // no error here
});

答案 1 :(得分:1)

使用此代码将起作用:

export class MyComponent implements OnInit {

public categoryData:string[] = [];

ngOnInit(): void {

}

 public loadDataFromServer() {

        let MyServerData = result.data;
        const crntData = this;
        MyServerData .forEach(function(item){
            crntData.categoryData.push(item.BarTitle); // error here
        });
    });
}