首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用angularjs的Google contacts

使用angularjs的Google contacts
EN

Stack Overflow用户
提问于 2014-11-05 10:38:09
回答 1查看 2.7K关注 0票数 0

我试图获取一个用户的谷歌联系人。我正在使用代码来实现auth2。

这是我的services.js

代码语言:javascript
复制
**Services.js** : ....
.service('googleService', ['$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/contacts/default/full',
domain = '{OPTIONAL DOMAIN}',
deferred = $q.defer();

this.login = function () {
    console.log("Inside login()");
    gapi.auth.authorize({ 
        client_id: clientId, 
        scope: scopes, 
        immediate: false,
        approval_prompt: "force"
    }, this.handleAuthResult);
    return deferred.promise;
}

this.handleClientLoad = function () {
    console.log("Inside handleClientLoad()");
    gapi.client.setApiKey(apiKey);
    gapi.auth.init(function () { });
    window.setTimeout(checkAuth, 1);
};

this.checkAuth = function() {
    console.log("Inside checkAuth()");
    gapi.auth.authorize({ 
        client_id: clientId, 
        scope: scopes, 
        immediate: true, 
    }, this.handleAuthResult);
};

this.handleAuthResult = function(authResult) {
    console.log("Inside handleResult()");
    if (authResult && !authResult.error) {
        var data = [];
        gapi.client.load('oauth2', 'v2', function () {
            var request = gapi.client.oauth2.userinfo.get();
            request.execute(function (resp) {
                data.push(resp.email);
                data.push(authResult.access_token);
                deferred.resolve(data);
            });
        });
        
    } else {
        deferred.reject('error');
    }
};

this.handleAuthClick = function() {
    console.log("Inside handleAuthClick()");
    gapi.auth.authorize({ 
        client_id: clientId, 
        scope: scopes,
        immediate: false,
        approval_prompt: "force"
    }, this.handleAuthResult);
    return false;
};

this.makeContactList = function(root){
    var plist = [];
    var contactsList = root.feed.entry;     
    if (contactsList != null && contactsList.length > 0) {
        for (var i = 0; i < contactsList.length; i++) {
            var contact = contactsList[i];
            var fname = "";
            var l = contact.gd$email;
            var address = null;
            var emailArr = [];
            if (l != null && l.length > 0) {
                var el = l[0];
                if (el != null) {
                    address = el.address;
                }
                if (l.length > 1) {
                    for (var k = 1; k < l.length; k++) {
                        var e = l[k];
                        if (e != null) {
                            emailArr[k - 1] = e.address;
                        }
                    }
                }
            }
            var lname = "";
            var dispName = contact.title.$t;
            if (dispName != null) {
                var sarr = dispName.split(' ');
                if (sarr.length > 0) {
                    if (sarr.length >= 1) {
                        fname = sarr[0];
                    }
                    if (sarr.length >= 2) {
                        for (var k = 1; k < sarr.length; k++) {
                            lname = lname +" "+sarr[k];
                        }
                        lname = lname.trim();
                    }
                }
            }
            var id = contact.id.$t;

            if (address != null && address.length > 0) {
                var p = {
                        firstName : "",
                        lastname : "",
                        email : "",
                        displayName : "",
                        otherEmails : [],
                        id : ""
                }
                p.firstName = fname;
                p.lastName = lname;
                p.email = address;
                p.displayName = dispName;
                p.otherEmails = emailArr;
                p.id = id;
                plist.push(p);
            }
        }
    } else {
        console.log("No contacts were obtained from the feed");
    }
    return plist;
};
this.disconnectUser = function(access_token){
    var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +access_token;
    $.ajax({
        type : 'GET',
        url : revokeUrl,
        async : false,
        contentType : "application/json",
        dataType : 'jsonp',
        success : function(nullResponse){
            console.log("Successfully disconnected access_token");
        },
        error : function(e){
            console.log("Failed to isconnect access_token");
            window.location.reload();
        }
    });
}
}]);

和controller.js

代码语言:javascript
复制
.controller('ContactsController',  ['$scope','$window','$modal','$http', 'ContactsFactory','googleService','ImportFactory','NotifyFactory', function($scope, $window, $modal, $http, ContactsFactory, googleService, ImportFactory, NotifyFactory) {

$scope.login = function () {
    var promise =  googleService.login()
    promise.then(function (data) {
        if(angular.isObject(data) && data[0]!== undefined && data[1]!== undefined){
            console.log(data[0]);
            console.log(data[1]);
            $http.get("https://www.google.com/m8/feeds/contacts/"+data[0]+"/full?alt=json&access_token=" + data[1] + "&max-results=1000&v=3.0")
            .success(function(data, status, headers, config) {
                console.log("In success");
                var contactList = googleService.makeContactList(data);
                var response = MyFactory.post(contactList);
                response.$promise.then(function(data){
                    console.log(data);
                    NotifyFactory.success("Successfully synched with your google contacts!");
                    googleService.disconnectUser(access_token);
                    //$route.reload();
                    window.location.reload();
                });
            })
            .error(function(data, status, headers, config) {
                console.log("In error");
                console.log(data);
                NotifyFactory.error("Something went wrong. Please try again.11111111111");
            });
        }else{
            NotifyFactory.error("Something went wrong. Please try again.2222222222222");
        }
    }
    , function (err) {
        console.log('Failed: ' + err);
        NotifyFactory.error("Something went wrong. Please try again.333333333333");
    });
};

当用户按下“获取联系人”按钮时,将调用$scope.login()。从某种意义上说,这是很好的工作方式,我可以通过一些方法获取登录到google帐户中的联系人。

当我按下按钮时,谷歌的登录屏幕就会弹出。输入abc@gmail.com的密码并按“Accept”,然后googleService.Login()返回一个空对象,并显示错误消息。

然后再按Get联系人按钮,甚至在我在同意屏幕上按“接受”之前(每次我给出一个额外的参数来强制同意),abc@gmail.com的联系人就会被获取。.I在同意屏幕上按“接受”

当我第三次按Get联系人按钮时,在我按接受键之前,abc@gmail.com的联系人会再次被取回来。我将同意屏幕上的电子邮件更改为xyz@gmail.com并按接受键。

然后,我再次按Get联系人按钮a,在同意屏幕上,请求abc@gmail.com,而不是xyz@gmail.com,我将其更改为xyz@gmail.com。尽管如此,abc@gmail.com的联系人仍然是在Get联系人按钮的所有后续按键上获取的。

我真的不明白在服务中控制的原因,也不明白为什么我的“联系人”会做一些疯狂的事情。请帮帮我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-05 10:48:27

我不知道这是否修复了所有错误,但我很确定,在将数据添加到数据数组之后,应该在request.execute的成功处理程序中调用request.execute

代码语言:javascript
复制
this.handleAuthResult = function(authResult) {
    console.log("Inside handleResult()");
    if (authResult && !authResult.error) {
        var data = [];
        gapi.client.load('oauth2', 'v2', function () {
            var request = gapi.client.oauth2.userinfo.get();
            request.execute(function (resp) {
                data.push(resp.email);
                data.push(authResult.access_token);
                deferred.resolve(data);
            });
        });
    } else {
        deferred.reject('error');
    }
};

否则,当用户登录时,您的登录承诺将继续,但是如果数据数组仍然是空的,则会导致错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26755078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档