Using Google API in Angular 2/TypeScript Using Google API in Angular 2/TypeScript angular angular

Using Google API in Angular 2/TypeScript


Change

.then(function () {      // Listen for sign-in state changes.    gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSigninStatus);      // Handle the initial sign-in state.      this.updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());    });

to

.then(()=> {      // Listen for sign-in state changes.    gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSigninStatus.bind(this));      // Handle the initial sign-in state.      this.updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());    });

if you use function your this will not refer to your component and passing a function as a parameter like .listen(this.updateSigninStatus); will also make the outer this to be binded to this function.

I suggest you to read: How to access the correct `this` context inside a callback?


After messing around with this, I found that a better sample for my use case was this one: https://cloud.google.com/compute/docs/tutorials/javascript-guide

Note that I am using the first suggestion as well:

gapi.auth2.getAuthInstance().isSignedIn.listen(status => this.updateSigninStatus(status));

I was able to get everything working after I realized that I had to init gapi.auth with everything I wanted the first time--I thought I could just authorize again later with different scopes. I'm now doing it in index.html like this:

    var PROJECT_ID = 'projectname';    var CLIENT_ID = 'xxxx.apps.googleusercontent.com';    var API_KEY = '1234';    var SCOPES = 'https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.readonly';    /**    * Authorize Google Compute Engine API.    */    function authorization() {      gapi.client.setApiKey(API_KEY);      gapi.auth.authorize({        client_id: CLIENT_ID,        scope: SCOPES,        immediate: false      }, function(authResult) {          if (authResult && !authResult.error) {            window.alert('Auth was successful!');          } else {            window.alert('Auth was not successful');          }        }      );     }