谷歌使用angularjs联系API



我正在尝试获取一个用户的Google联系人。我正在使用此代码来实现auth2。

这是我的服务。js

**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();
        }
    });
}
}]);

和控制器.js

.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()是在用户按下"键时调用的;获取联系人";按钮这工作得很好,因为我知道如何获得登录谷歌帐户的联系人。

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

然后我再次按下"获取联系人"按钮abc@gmail.com甚至在我按下同意屏幕上的"接受"之前就被提取了(我在auth中提供了一个额外的参数,以每次强制同意)。我在同意屏幕上按下"接受"

第三次按下"获取联系人"按钮时abc@gmail.com在我按下"接受"之前再次提取。我将同意屏幕上的电子邮件更改为xyz@gmail.com然后按accept。

然后我再次按下"获取联系人"按钮,在同意屏幕上,为abc@gmail.com被要求而不是xyz@gmail.com,我把它改成xyz@gmail.com.仍然是的联系人abc@gmail.com正在获取所有后续按下"获取联系人"按钮的联系人。

我真的不明白服务中的控制,也不明白为什么我的"获取联系人"是在做疯狂的事情。请帮帮我。

我不知道这是否修复了您的所有错误,但我敢肯定,在数据添加到数据数组后,您应该在request.execute的成功处理程序中调用deferred.resolve(data);

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');
    }
};

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

相关内容

  • 没有找到相关文章

最新更新