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