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

3

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)
        });
   }   
Sign up to request clarification or add additional context in comments.

1 Comment

Right. An alternative solution is to use .bind(this).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.