Search code examples
angulargoogle-signinangular6google-api-js-client

Angular 6 Google login - 'gapi.load is not a function' error


So of course I found a solution as I was writing this answer after hours of effort beforehand. The question is now why this would have worked in some environments and not others.

ORIGINAL QUESTION:

The following code works in Chrome incognito but not in non-incognito or Safari whether private/incognito or not.

What is more baffling is that it works for my colleagues in both browsers.

index.html

// have tried with 'async defer'
<script src="https://apis.google.com/js/platform.js"></script>

login.component.ts

declare const gapi: any;
...
 ngAfterViewInit() {
  // just to be sure gapi has loaded. have tried without timeout
  setTimeout(() => this.googleInit(), 1000);
}
googleInit() {
  gapi.load('auth2', () => {    // error here
    this.auth2 = gapi.auth2.init({

Chrome ERROR

ERROR TypeError: gapi.load is not a function
at LoginComponent.push../src/app/login/login.component.ts.LoginComponent.googleInit (login.component.ts:36)


SOLUTION: adding the following to index.html:

<script src="https://apis.google.com/js/api.js"></script>

This is not in the official google guide and is missing from most examples I have found. I am interested to know why it was necessary here.


Solution

  • To use the google api module we have to import

    <script src="https://apis.google.com/js/api.js"></script>
    

    That's also mentioned in official docs as well :

    https://developers.google.com/api-client-library/javascript/samples/samples