Search code examples
angulartypescriptcallbackpromisegoogle-api-js-client

Angular2 cannot access this in promise callback


This is really strange, but here is my snippet within a service:

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

This code is called when the service is constructed. believe it or not, the status => this.updateGoogleSigninStatus(status) works, but I get an error on the next line, where it cannot seem to see the function. Bazaar scoping problem.

Cannot read property 'updateGoogleSigninStatus' of undefined

If I move that line out of the promise, it works.


Solution

  • 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.