javascript - 加载 Google Client api gapi 和 angular js 的正确顺序

标签 javascript angularjs google-api-js-client

如何将 js 文件与 Google Client js api 一起加载到 Angular 项目中有点棘手。

这道题说的是做这件事的正确顺序。 Angular Js and google api client.js (gapi)

有一个官方文档在谈论这个, https://cloud.google.com/developers/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications/ .

文档中的一件事是它在 init 内部使用 window.init() ,这将导致无限循环。

正如 willlma 指出的,我们应该为该函数使用不同的名称。

但是我遇到了一个错误 未捕获的类型错误:window.initGAPI 不是函数

该项目是使用 angular 的 yeoman 生成器创建的。

index.html中加载js的顺序

<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(仅此文件的后半部分):

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

主要.js:

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

我测试了一些日志,发现在加载调用window.init的cliet.js之前执行了$window.initGAPI的定义,但是在window.init内部,并没有定义window.initGAPI。似乎在主 Controller 中,为对象窗口定义一个名为 initGAPI 的函数失败了。

最佳答案

我认为以各自的方式正确加载两个库并不是那么容易,因为它们以不同的方式异步。 相反,让一个加载另一个更容易。

第一种也是更简单的方法是将 client.js 库放在所有脚本的末尾,然后在 Google 库完全加载时执行手动 Angular Bootstrap 。

其他方法可能相反,所以让 Angular 创建 Google client.js 脚本标签并加载库。

检查此项目:https://github.com/canemacchina/angular-google-client 我创建了这个库来帮助我在 Angular 中使用 Google 客户端库,它使用第二种方法...

关于javascript - 加载 Google Client api gapi 和 angular js 的正确顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524300/

相关文章:

javascript - 使用生成的数字为对象的左侧位置设置动画

javascript - 在过滤器中注入(inject) HTML - angularJS

angularjs - 找不到模块 'node-sass' 中的错误

javascript - 将对象从 jade 传递到 angularjs 模板

javascript - 数组中的 Google 电子表格

javascript - 序列化一个javascript类对象?

javascript - 提交时更改输入背景

javascript - 谷歌驱动器范围 'Error Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.'

javascript - 如何修复来自 Google Drive API 的 'The resource body includes fields which are not directly writable' 警告?

javascript - 使用handlebars js和marionette js保存表单数据