Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from AngularJS service to controller with Google API?

I'm trying to use the Google API Javascript client to utilize Google Login on my app, and then access the user's email address and contacts. I'm combining this with AngularJS, and I've read that it's best to make this its own Service.

Here is the code for the service so far:

.service('googleLogin', ['$http', '$rootScope', function ($http, $rootScope) {
            var clientId = '{MY CLIENT KEY}',
                apiKey = '{MY API KEY}',
                scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds',
                domain = '{MY COMPANY DOMAIN}';

            this.handleClientLoad = function () {
                // Step 2: Reference the API key
                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) {
                    gapi.client.load('oauth2', 'v2', function () {
                        var request = gapi.client.oauth2.userinfo.get();
                        request.execute(function (resp) {
                            console.log(userEmail);
                        });
                    });
                }
            };

            this.handleAuthClick = function (event) {
                // Step 3: get authorization to use private data
                gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false, hd: domain }, this.handleAuthResult );
                return false;
            };

        }]);

I then call this from the controller with the following:

        $scope.login = function () {
            googleLogin.handleAuthClick();
        };

Which works, and the API is called properly. But now, I'm not sure how to get data from the API through the Service. I need to get the user's email address, as well as a list of their contacts. I can't just have separate get functions that return these values, because it seems like the API client calls must be made in chains (for example, handleAuthResult is called as a parameter in handleAuthClick).

I've also tried setting them as $rootScope values, or just normal variables, but once the controller calls them they always come as undefined.

Am I approaching this correctly? How can I get these variables from the Google API, to the Service, to the Controller? Thanks.

like image 289
Jakemmarsh Avatar asked Mar 26 '26 10:03

Jakemmarsh


1 Answers

I ended up using the promise/defer implementation from angularJS, documented here.

Here's the final service:

.service('googleLogin', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
            var clientId = '{MY CLIENT ID}',
                apiKey = '{MY API KEY}',
                scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds',
                domain = '{MY COMPANY DOMAIN}',
                userEmail,
                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) {
                            $rootScope.$apply(function () {
                                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;
            };

        }]);

And how it's currently called in the controller:

var promise = googleLogin.login();
                promise.then(function (data) {
                    console.log(data.email);
                }, function (reason) {
                    console.log('Failed: ' + reason);
                });
like image 174
Jakemmarsh Avatar answered Mar 28 '26 01:03

Jakemmarsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!