我需要将数据合并/推送到对象中。
我的代码是:
export class HeaderComponent implements OnInit {
site_heading = "Business Casual";
menubar = [];
isLogged = true;
constructor() {
this.menubar = [{
'link': 'home',
'name': 'Home'
}, {
'link': 'about',
'name': 'About'
}, {
'link': 'store',
'name': 'Store'
}, {
'link': 'products',
'name': 'Products'
}];
let userMenu = [{
'link': 'myprofile',
'name': 'My Profile'
}, {
'link': 'logout',
'name': 'LogOut'
}];
userMenu.forEach(function(value) {
this.menubar.push(value);
});
}
ngOnInit() {}
}
显示错误:
ERROR TypeError: Cannot read property 'menubar' of undefined
最佳答案
您需要使用箭头函数而不是常规函数,以确保this
上下文正常:
...
userMenu.forEach((value) => {
this.menubar.push(value);
});
...
关于javascript - 将数据推送到对象时出现 Angular 4 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51438840/