[英]Angular 4 error in pushing data into object
I need to merge/push data into object. 我需要将数据合并/推入对象。
My code is: 我的代码是:
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() {}
}
Its showing error: 其显示错误:
ERROR TypeError: Cannot read property 'menubar' of undefined
错误TypeError:无法读取未定义的属性“菜单”
You need to use an arrow funciton instead of a regular function, to ensure this
context is OK: 您需要使用箭头功能而不是常规功能,以确保
this
上下文正常:
...
userMenu.forEach((value) => {
this.menubar.push(value);
});
...
This should work: 这应该工作:
let self = this
userMenu.forEach(function (value) {
self.menubar.push(value);
});
Or lambda expressions (arrow functions) 或lambda表达式(箭头功能)
Use an arrow function, 使用箭头功能,
Arrow function is anonymous and doesn't bind its own this. 箭头函数是匿名的,不会对此进行绑定。 Hence, this is this of current context.
因此,这就是当前情况。
userMenu.forEach((value) => {
this.menubar.push(value);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.