【问题标题】:Importing Google contacts with angularjs使用 angularjs 导入 Google 联系人
【发布时间】:2016-06-27 08:59:57
【问题描述】:

我正在尝试使用 Angular Js 导入用户的 gmail 联系人。该代码在纯 javascript 中运行良好,但在 angular js 中出现错误。

HTML 代码..

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

角度代码..

   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 和密码后,控制台中会显示以下错误消息..

  Uncaught ReferenceError: authorizationResult is not defined

无法理解我哪里出错了,因为这段代码在 Javascript 中运行。请帮助..

【问题讨论】:

  • 你确定是运行的代码吗?在这段代码中它不能得到这个错误。
  • 也许你必须刷新/重新加载你的代码

标签: javascript angularjs google-api google-contacts-api


【解决方案1】:

这是使用 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 - &lt;script src="https://apis.google.com/js/client.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    问题在于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 代码现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多