2016-09-19 2 views
4

간단한 방법이 있지만 찾을 수없는 것 같습니다. 여기Angular2 : 익명 함수 내에서 클래스 변수에 액세스

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); 
     }, 

    }); 

} 
} 

문제 내 코드는 다음으로 onSuccess 콜백에서 나는 그것이 부모 클래스의 속한 this.authService 변수에 액세스 할 수 없습니다.

답변

9

function()this의 범위를 변경하므로 사용하지 마십시오.

배열 기능이있어 문제가 성공 콜백 함수가 다른 어휘 환경에 있다는 this

onSuccess: (result: any) => { 
     this.authService.login(this.user, result); 
    }, 
    onFailure: (err: any) => { 
     console.log(err.message); 
    }, 
4

의 범위를 유지한다. 이것이 ES6에서 화살표 기능을 사용하여 함수를 정의 할 수있는 이유입니다.

onSuccess:(result: any) => { 
     this.authService.login(this.user, result); 
} 

또는 할당 ES5 구문 기능의 범위에 가변이 :

var self = this; 

onSuccess: function(result: any) { 
    self.authService.login(this.user, result); 
} 
관련 문제