Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use AngularJS with Google API JavaScript Client?

I am wondering how I would convert this Google API JavaScript Sample code into an AngularJS app. I thought it would be really neat.

And as a follow-up how would it work with Oauth 2.0?

Thanks.

I tried using the angularjs seed app and modified it like this -

// controller.js

function SampleListCtrl ( $scope, $http ){
  $http.
  jsonp( 'https://apis.google.com/js/client.js?onload=JSON_CALLBACK' ).
  success( function () {
    alert( 'go go GO' );
    function makeRequest () {
    var request = gapi.client.urlshortener.url.get({
      'shortUrl': 'http://www.google.com/'
    });

   request.execute( function(response) {
       $scope.longUrl = response.longUrl;
     });
   }

    gapi.client.setApiKey( 'XXXX' );
    gapi.client.load( 'urlshortener', 'v1', makeRequest );

    $scope.samples = data.feed.entry;
  });
};

And in index.html

<div ng-controller="SampleListCtrl">
    <h4>{{ longUrl }}</h4>
</div>

RE: Roy Truelove's tip I have tried adding an error callback which is firing

error( function () {
  console.log( JSON.stringify( arguments ) );
});

I wasn't sure what would come back so I inspected the arguments object and so the output in the console is -

{"1":0,"3":{"method":"JSONP","url":"https://apis.google.com/js/client.js?onload=JSON_CALLBACK"}}

The alert does not fire meaning that the callback didn't work. How do I get that to work? Is there a better approach?

like image 480
Peter Avatar asked Jun 13 '26 13:06

Peter


1 Answers

You are requesting JSON but load a javascript library, right? I don't think the http service is made for that. You would need to either load the script before bootstrapping Angular or integrate a script loader to dynamically load it.

If you are anyway using the Angular Seed template than you can just add the google API to the scripts in the index.html or use the asynchronous loader.

like image 76
F Lekschas Avatar answered Jun 16 '26 02:06

F Lekschas