I'm sure there is a simple way to do this but I can't seem to find it. Here is my code
export class UserLoginComponent {
private user: User;
public authService: AuthService;
constructor(private cognitoConfigs: CognitoUtil, authService: AuthService) {
this.user = new User();
this.authService = authService;
}
authenticate() {
// Some work being done here
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result: any) {
this.authService.login(this.user, result);
},
onFailure: function(err: any) {
console.log(err.message);
},
});
}
}
Problem: In the onSuccess callback I can't access the this.authService
variable which belongs to it's parent class.
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);
},
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With