2016-09-19 5 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); 
}