0

Using Angular2

I get json response with a list of actions/moves.

  • If the action type is move, assign it to movesForward array;
  • If the action type is fight, assign it to actions array;

    public movesForward = [];public actions = [];

     ngOnInit() { this.userData.actions.forEach(function(entry) { switch(entry.type) { case "move": this.movesForward.push(entry); break; case "fight": this.actions.push(entry); break; } }); } 

    My problem is that the foreach is inside inner function and I can't access my public variables in this function.

    TypeError: Cannot read property 'movesBack' of undefined

  • I'm not interested in using pipes since its one-time use only in one component.

How I can access my main class variables inside my foreach?

    1 Answer 1

    4

    Just use ()=> instead of function() (if you are using TS or ES6)

     ngOnInit() { this.JwtService.userData.zone.actions.forEach((entry) => { switch(entry.type) { case "move": this.movesForward.push(entry); break; case "fight": this.actions.push(entry); break; } }); } 

    or in ES5

     ngOnInit() { this.JwtService.userData.zone.actions.forEach((function (entry){ switch(entry.type) { case "move": this.movesForward.push(entry); break; case "fight": this.actions.push(entry); break; }).bind(this) }); } 
    1
    • Right. An alternative solution is to use .bind(this).CommentedMay 13, 2016 at 10:44

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.