使用AngularJS获取facebook好友列表

时间:2014-09-02 05:15:41

标签: javascript facebook angularjs facebook-graph-api

我是AngularJS的新手。我正在尝试使用AngularJS获取用户的Facebook好友列表的一些代码,我在这里找到了一些代码AngularJS@1.0.1 with Facebook

在我的index.html文件中:

     <!DOCTYPE html>
      <html ng-app="funwithfb">
      <head> 
        <meta charset="utf-8">
        <title>FB With Angular</title>
        <link rel="stylesheet" href="css/bootstrap.css">
      </head>

      <body ng-controller="MainController">
        <div id="fb-root"></div>
        <div class="ng-cloak" ng-show="user.connected">
          Hello {{user.first_name}}!
        </div>

        <div class="ng-cloak" ng-hide="user.connected">
          One moment please...
        </div>

        <script src="http://connect.facebook.net/en_US/all.js"></script>
        <script type="text/javascript">
          FB.init({
            appId      : '272951952842742',
            xfbml      : true,
            version    : 'v2.0',
          });
        </script>
        <script src="js/angular.min.js"></script>
        <script src="js/app.js"></script>
        </body>
      </html>

在我的app.js文件中:

 var app=angular.module('funwithfb',[]);

  app.controller('MainController',function($scope,Facebook){
    $scope.user=Facebook.getUser(FB);
    console.log($scope.user);
  });
  app.service('Facebook', function($q, $rootScope) {

    // resolving or rejecting a promise from a third-party
    // API such as Facebook must be
    // performed within $apply so that watchers get
    // notified of the change
    resolve = function(errval, retval, deferred) {
      $rootScope.$apply(function() {
        if (errval) {
          deferred.reject(errval);
        } else {
            console.log(retval);
          retval.connected = true;
          console.log(retval);
          deferred.resolve(retval);
        }
      });
    }

    return {
      getUser: function(FB) {
        var deferred = $q.defer();
        FB.getLoginStatus(function(response) {
          if (response.status == 'connected') {
            FB.api('/me', function(response) {
              resolve(null, response, deferred);
            });
          } else if (response.status == 'not_authorized') {
            FB.login(function(response) {
              if (response.authResponse) {
                FB.api('/me', function(response) {
                  resolve(null, response, deferred);
                });
              } else {
                resolve(response.error, null, deferred);
              }
            });
          } 
        });
        promise = deferred.promise;
        promise.connected = false;
        return promise;
      }
    }; 
  });

我的问题是 -

  1. 虽然已连接Facebook响应,但此代码始终将user.connected返回为false 。这段代码有什么问题?
  2. 这种情况下如何延迟服务异步操作?

1 个答案:

答案 0 :(得分:0)

这段代码实际上工作正常。您需要做的就是添加&#34; http://plnkr.co/&#34;到您在Facebook注册的应用程序的应用程序域。