Bhunesh  Satpada
Bhunesh Satpada

Reputation: 810

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

Upvotes: 1

Views: 42

Answers (3)

Sajeetharan
Sajeetharan

Reputation: 222682

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);
});

Upvotes: 0

Grenther
Grenther

Reputation: 476

This should work:

let self = this
userMenu.forEach(function (value) {
    self.menubar.push(value);
});

Or lambda expressions (arrow functions)

Upvotes: 2

Thor Jacobsen
Thor Jacobsen

Reputation: 8851

You need to use an arrow funciton instead of a regular function, to ensure this context is OK:

...
userMenu.forEach((value) => {
    this.menubar.push(value);
});
...

Upvotes: 3

Related Questions