The correct order to load Google Client api gapi and angular js

北战南征 提交于 2019-12-11 13:14:46

问题


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.


回答1:


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




回答2:


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
    }
 }  


来源:https://stackoverflow.com/questions/31524300/the-correct-order-to-load-google-client-api-gapi-and-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!