Angular2无法在promise回调中访问它

时间:2018-04-19 07:18:10

标签: angular typescript callback promise gapi

这真的很奇怪,但这是我服务中的代码段:

constructor() {
    gapi.load('client:auth2', this.loadGoogleApi);
}


private loadGoogleApi() {

    // Array of API discovery doc URLs for APIs used by the quickstart
    var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

    // Authorization scopes required by the API; multiple scopes can be
    // included, separated by spaces.
    var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";

    //init google api 
    gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
    }).then(() => {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(status => this.updateGoogleSigninStatus(status));
        // Handle initial sign in state
        this.updateGoogleSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get())
    });
}

构造服务时会调用此代码。 信不信由你,status => this.updateGoogleSigninStatus(status)有效,但我在下一行遇到错误,似乎无法看到该功能。 Bazaar范围问题。

Cannot read property 'updateGoogleSigninStatus' of undefined

如果我将这条线移出承诺,那就行了。

1 个答案:

答案 0 :(得分:1)

loadGoogleApi is passed as callback and should be treated accordingly in order to maintain proper this.

It's either:

constructor() {
    this.loadGoogleApi = this.loadGoogleApi.bind(this);
    gapi.load('client:auth2', this.loadGoogleApi);
}


private loadGoogleApi() { ... }

Or:

constructor() {
    gapi.load('client:auth2', this.loadGoogleApi);
}

private loadGoogleApi = () => { ... }

The former is generally preferable for the reasons explained in this answer.