export class myclass implements OnInit {
private outagesList;
private outageArray;
constructor(private outages: OutagesService){}
ngOnInit(){
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
this.outagesList.forEach( function (arrayItem)
{
this.outageArray.push(arrayItem["title"]);
});
)
}
如果我尝试将数据推送到outageArray,则会抛出ERROR TypeError: Cannot read property 'outageArray' of undefined
如何避免此错误?我需要将此outageArray值访问为html。
答案 0 :(得分:2)
使用箭头功能
this.outagesList.forEach((arrayItem) => {
this.outageArray.push(arrayItem["title"]);
});
答案 1 :(得分:-1)
使用post-ES6 Javascript后,forEach
等功能可能不是您的最佳解决方案。最简单的方法是使用for..of
循环:
this.outages.getOutagesList().subscribe((data) => {
this.outagesList = data;
for (let arrayItem of this.outagesList)
{
this.outageArray.push(arrayItem.title);
});
)