Angular Js and google api client.js (gapi)

后端 未结 8 1482
不思量自难忘°
不思量自难忘° 2020-11-29 00:46

It took me one day to make it works so I think my experience may be useful from someone. And maybe some others will find improvement.

So I start angularJS two days a

相关标签:
8条回答
  • 2020-11-29 01:31

    I used a solution similar to willlma, but my application makes use of UI Router, so there's no knowing which controller will be called.

    I was able to solve this with a Javascript Promise.

    index.html

    <html ng-app="myApp">
    <head>
        <script src="angular.js" type="text/javascript"></script>
        <script src="app.js" type="text/javascript"></script>
        <script src="https://apis.google.com/js/client.js?onload=init">
    </head>
    

    app.js

    var app = angular.module('myApp', []);
    
    app.controller('MainController', function($scope, gapiService) {
        gapiService.then(function(gapi) {
            // You can use gapi normally here;
        });
    });
    
    app.service('gapiService', function($window) {
        return new Promise(function(resolve, reject) {
            if ($window.gapi !== undefined) {
                console.log("Have gapi already");
                resolve($window.gapi);
            } else {
                console.log("Waiting for gapi");
                $window.init = function() {
                    resolve($window.gapi);
                }
            }
        });
    });
    
    0 讨论(0)
  • 2020-11-29 01:34

    Nice post and thanks! This approach worked for me. It might matter what order that the code appears in your index.html file. It did not work for me until I had things inthis order.

    ...
    <script>
      function googleOnLoadCallback(){
          alert('googleOnLoadCallback called');
          var apisToLoad = 1; // must match number of calls to gapi.client.load()
          var gCallback = function() {
              if (--apisToLoad == 0) {
                  //Manual bootstraping of the application
                  var $injector = angular.bootstrap(document, ["myApp"]);
                  console.log("myApp bootstrap complete " + gapi);
              };
          };
          gapi.client.setApiKey("my_client_id");
          gapi.client.load("translate", "v2", gCallback);
    
      }
    </script>
    <!-- See https://developers.google.com/api-client-library/javascript/samples/samples -->
    <script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
    </head>
    
    0 讨论(0)
提交回复
热议问题