The correct order to load Google Client api gapi a

2019-08-15 06:31发布

It's kind of tricky how to load js files in an Angular project together with Google Client js api.

This question is talking about the correct order of doing this. Angular Js and google api client.js (gapi)

And there is an Official Doc talking about this, https://cloud.google.com/developers/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications/.

One thing in the doc is that it uses window.init() inside of init which will be causing an infinite loop.

As willlma pointed out, we should use a different name for the function.

But I have met an error of Uncaught TypeError: window.initGAPI is not a function

The project is created by using yeoman generator for angular.

The order of loading js in index.html

<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/about.js"></script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>

app.js(only the latter part of this file):

var init = function(){
    console.log("gapi init");
    window.initGAPI();
}

main.js:

angular.module('testApp')
  .controller('MainCtrl', function ($scope, $window) {
    $window.initGAPI = function(){
        console.log("controller inti");
    }
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });

I have put some logs to test and found that the definition for $window.initGAPI is executed before loading the cliet.js which calls window.init, but inside of window.init, window.initGAPI is not defined. It seems in the main controller, defining a function called initGAPI to object window failed.

2条回答
祖国的老花朵
2楼-- · 2019-08-15 06:58

I think is not so easy to correctly load both libraries each in its way, because both are asynchronous in a different way. Instead, is easier to let one load the other.

The first and simplier approach is to put the client.js lib at the end of all scripts, and then do a manual Angular bootstrap when the Google library is fully loaded.

Other method could be the opposite, so let Angular create the Google client.js script tag and load the library.

Check this project: https://github.com/canemacchina/angular-google-client I've create this library to help me using Google client library in Angular, and it use the second method...

查看更多
【Aperson】
3楼-- · 2019-08-15 07:12

I had a similar issue. Perhaps you can try something like this for the init function so that it retries again when the controller is not loaded yet.

 function init() {
    if (window.initGapi != undefined) {
        window.initGapi();
    }
    else {
        setTimeout(init, 500); // wait for 500 ms
    }
 }  
查看更多
登录 后发表回答