javascript - 将数据推送到对象时出现 Angular 4 错误

标签 javascript angular

我需要将数据合并/推送到对象中。
我的代码是:

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/

相关文章:

javascript - Angular 2 和 AmCharts

Angular 模板 : How to display the row item as a normal table row

javascript - 单击相同的元素但需要不同的变量/值?

javascript - 在 javascript 中显示 PHP 对象数据

angular - 谷歌本地 map 不适用于 ionic 3

angular - 无法读取 Visual Code 中未定义的属性 'thisCompilation'

html - Angular 9 Keyvalues 管道不是为生产而构建的

javascript - 通过 JSON/AJAX 更新 HTML

javascript - 无法获取 img 宽度和高度 jQuery

javascript - NodeJs + PhantomJs 从 page.evaluate 方法返回 JQuery 结果