使用angularjs导入Google通讯录

时间:2016-06-27 08:59:58

标签: javascript angularjs google-api google-contacts

我正在尝试使用Angular Js导入用户的Gmail联系人。代码在普通的javascript中运行良好,但在角度js中给出了错误。

HTML代码..

<a class="btn btn-primary btn-simple" ng-click="importgoogle()"><u>Import Gmail Friends</u></a>

Angular Code ..

   var clientId = 'Client ID';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
   $scope.importgoogle = function(){
    window.setTimeout(authorize);       //calls authorize()
}

var authorize = function(){
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);       //calls handleAuthorization()
}

var handleAuthorization = function(){
    if (authorizationResult && !authorizationResult.error) {
            $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
            function(response){
                console.log(response);
                });
        }
}

输入用户的ID&amp;密码控制台中显示以下错误消息..

  Uncaught ReferenceError: authorizationResult is not defined

无法理解我出错的地方,因为此代码在Javascript中工作。请帮助..

2 个答案:

答案 0 :(得分:2)

以下是使用Angular Js的工作示例:

app.controller("importGCCtrl", function($scope, $http) {
$scope.config = {
    'client_id': 'Client ID',
    'scope': 'https://www.google.com/m8/feeds'
};

$scope.inviteContacts = function() {
    gapi.auth.authorize($scope.config, function() {
        $scope.fetch(gapi.auth.getToken());
    });
}

$scope.fetch = function(token) {
    $http.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json").then(function(response) {
        console.log(response);
        //console.log(response.data.feed.entry);
        //$scope.contacts = response.data.feed.entry; // to assign data
    });
}

});

*注意:请确保您已在页面上添加了API <script src="https://apis.google.com/js/client.js"></script>

答案 1 :(得分:0)

问题在于handleAuthorization函数。实现该功能的正确方法是..

 var handleAuthorization = function(authorizationResult){         //authorizationResult needs to be passed as an arguement.
if (authorizationResult && !authorizationResult.error) {
        $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
        function(response){
            console.log(response);
            });
    }

}

进行此更改后,Angular Js代码现在正常运行。