Angular2: Access class variable within anonymous function
The problem here is that the success callback function is in a different lexical environment. This is why in ES6+ functions can be defined using arrow functions =>.
onSuccess:(result: any) => {
this.authService.login(this.user, result);
}
or assign this to a variable outside the scope of the function with the ES5 syntax:
var self = this;
onSuccess: function(result: any) {
self.authService.login(this.user, result);
}
Don't use function ()
because it changes the scope of this
.
Arrow functions retain the scope of this
onSuccess: (result: any) => {
this.authService.login(this.user, result);
},
onFailure: (err: any) => {
console.log(err.message);
},