vsav vsav - 5 months ago 20
Javascript Question

Angular2 setting a user asynchronously?

I am trying to pull a user's information and set it to my user variable as follows. I am using the angular-fullstack boilerplate.

this.getCurrentUser = this.Auth.getCurrentUser;
this.getCurrentUser(function(data){
console.log('data: ', data);
this.username = data.name;
});


But when doing so, I get an error that
this.username
is not defined. Thus, my question is how can I put the relevant information into my variable.

Answer

Try using an arrow function expression for the callback since

Arrow functions capture the this value of the enclosing context

this.getCurrentUser = this.Auth.getCurrentUser;
this.getCurrentUser(data => {
    console.log('data: ', data); 
    this.username = data.name;
});