Angular2 无法在承诺回调中访问它

Angular2 cannot access this in promise callback

这真的很奇怪,但这是我在服务中的片段:

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) 有效,但我在下一行收到一个错误,它似乎看不到函数。集市范围界定问题。

Cannot read property 'updateGoogleSigninStatus' of undefined

如果我将该行移出 promise,它就会起作用。

loadGoogleApi 作为回调传递,应进行相应处理以保持适当的 this.

它是:

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


private loadGoogleApi() { ... }

或:

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

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

由于 中解释的原因,前者通常更可取。