Joshua Kissoon Joshua Kissoon - 1 year ago 114
TypeScript Question

Angular2: Access class variable within anonymous function

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) {



Problem: In the onSuccess callback I can't access the
variable which belongs to it's parent class.

Answer Source

Don't use function () because this changes the scope of this.

Array functions retain the scope of this

    onSuccess: (result: any) => {
        this.authService.login(this.user, result);
    onFailure: (err: any) => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download