Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

javascript - Angular Js and google api client.js (gapi)

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 ago. And I want it works with Google Cloud Endpoints to create a backend interface. Here comes the trouble for me.

The javascript client for gapi comes with asynchronous loading, so angular initialization will crash having gapi undefined.

So you need to bootstrap angular when gapi is initialized:

  1. remove ng-app="myApp"
  2. Add <script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
  3. Add the callback:

    function googleOnLoadCallback(){  
        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('Angular bootstrap complete ' + gapi);  
            };  
        };  
        gapi.client.load('helloWorld', 'v1', gCallback, '//' + window.location.host + '/_ah/api');  
    }
    

Feel good but how about a call ?

So here is the controller:

angular.module('myApp.controllers', []).  
    .controller('MyCtrl', ['$scope' ,'helloWorldService',  
        function($scope,greetingsService) {
          helloWorldService.loadData($scope);  
    }]);

And here is the service:

angular.module('myApp.services', [])
service('helloWorldService', [function() {
   this.loadData = function($scope)  {
     //Async call to google service
     gapi.client.helloWorld.greetings.listGreeting().execute(
        function(resp) {
            if (!resp.code) {
                console.debug(resp);
                $scope.greetings = resp.items;
                // Because it's a callback,
                // we need to notify angular of the data refresh...
                $scope.$apply();
            }
      });
   };
}]);

And magically your page updates thanks to angular.

Feel free to mark anywhere I go wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...