public
Last active

AngularJS Service with Controller for access to Google API with Javascript Client (and RequireJS)

  • Download Gist
controllers.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
define(['angular', 'services'], function (angular) {
'use strict';
 
return angular.module('myApp.controllers', ['myApp.services'])
.controller('IndexCtrl', ['$scope', 'googleService' function ($scope, googleService) {
 
$scope.login = function () {
googleService.login().then(function (data) {
// do something with returned data
console.log(data.email);
}, function (err) {
console.log('Failed: ' + err);
});
};
 
 
}]);
});
services.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
define(['angular'], function (angular) {
'use strict';
 
angular.module('myApp.services', [])
.service('googleService', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
var clientId = '{CLIENT_ID}',
apiKey = '{API_KEY}',
scopes = '{SCOPES}',
domain = '{OPTIONAL DOMAIN}',
deferred = $q.defer();
 
this.login = function () {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false,
hd: domain
}, this.handleAuthResult);
 
return deferred.promise;
}
 
this.handleClientLoad = function () {
gapi.client.setApiKey(apiKey);
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
};
 
this.checkAuth = function() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true,
hd: domain
}, this.handleAuthResult);
};
 
this.handleAuthResult = function(authResult) {
if (authResult && !authResult.error) {
var data = {};
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function (resp) {
data.email = resp.email;
});
});
deferred.resolve(data);
} else {
deferred.reject('error');
}
};
 
this.handleAuthClick = function(event) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false,
hd: domain
}, this.handleAuthResult);
return false;
};
 
}]);
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.