angularjs - 使用 Google API 将变量从 AngularJS 服务传递到 Controller ?

标签 angularjs google-api google-oauth google-api-java-client

我正在尝试使用 Google API Javascript 客户端在我的应用上使用 Google 登录,然后访问用户的电子邮件地址和联系人。我正在将它与 AngularJS 结合起来,并且我已经读到最好将它作为自己的服务。

这是目前服务的代码:

.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;
            };

        }]);

然后我从 Controller 调用它:

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

哪个有效,并且 API 被正确调用。但是现在,我不确定如何通过服务从 API 获取数据。我需要获取用户的电子邮件地址,以及他们的联系人列表。我不能只使用单独的 get 函数来返回这些值,因为似乎 API 客户端调用必须在链中进行(例如,handleAuthResult 被称为handleAuthClick 中的参数)。

我也尝试将它们设置为 $rootScope 值,或者只是普通变量,但是一旦 Controller 调用它们,它们总是以 undefined 的形式出现。

我的处理方法正确吗?如何从 Google API 到 Service 再到 Controller 获取这些变量?谢谢。

最佳答案

我最终使用了来自 angularJS 的 promise/defer 实现,记录在 here .

这是最后的服务:

.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;
            };

        }]);

以及它当前在 Controller 中的调用方式:

var promise = googleLogin.login();
                promise.then(function (data) {
                    console.log(data.email);
                }, function (reason) {
                    console.log('Failed: ' + reason);
                });

关于angularjs - 使用 Google API 将变量从 AngularJS 服务传递到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174748/

相关文章:

r - 努力在 shinyapps.io 中使用我自己的 API key 和 googlesheets4

java - Google Drive API Android/Java - 文件列表始终为空

javascript - 是否可以在 AngularJS 中模拟按键?

javascript - 使用 $cordova Oauth 问题登录

javascript - 具有相同路由的 AngularJs 动态模板显示

google-apps-script - "Authorisation is required to perform that action"消息,即使在单击 "Allow"之后

google-chrome-extension - 如何使用JavaScript从Google日历页面获取事件ID?

azure - 如何将 Google OAuth 2 token 传递给 Azure API 身份验证?

php - 尝试使用 Google OAuth 2.0 登录混合流程时出错(Google_IO_Exception',消息为 'HTTP Error: Unable to connect: ' 0'')

javascript - angularjs 和 localStorage 更改事件