Ui.Router在FB Init之后解析Window.FB

时间:2015-01-26 16:00:24

标签: angularjs facebook

问题 嗨,我希望我的stateProvider等到Facebook初始化。然后它应该将$window.FB var分配给我的控制器。

我采用这种方法作为方向: How to detect when facebook's FB.init is complete

App.js

module.config(['$urlRouterProvider', '$stateProvider' ,function($urlRouterProvider, $stateProvider) {
$stateProvider
    .state('share',{
      url:'/share',
      templateUrl:'modules/Share/Share.html',
      controller: 'ShareCtrl',
      controllerAs:'shareCtrl',
      data: {
        auth: "LoggedIn"
      },
      resolve: {
        FB: ['$window', function($window){
          return $window.FB.getUserID(function(response){
            return 'test';
            // return $window.FB;
          });     
        }]
      }
    });
}]);

...

module.run(['$rootScope', '$state', 'authUserService', '$FB', function($rootScope, $state, authUserService, $FB) {
  $FB.init('475092975961783', './Modules/Social/FB-Channel.html');

}]);

我的Facebook初始化功能与此处基本相同: https://github.com/djds4rce/angular-socialshare/blob/master/angular-socialshare.js 除此之外,我传递了一个关于channel.html的网址(我认为甚至不再需要它,Is channelUrl parameter for Facebook init() deprecated?)。

控制器

module.controller('ShareCtrl', ['$scope', 'myFacebookService', 'FB', function($scope, myFacebookService, FB) {
    this.rootUrl = 'modules/Share/';
     console.log(FB);
     // console.log(myFacebookService.getUser(FB));
}]);

变量永远不会被解析,视图永远不会被加载。浏览器控制台中的window.FB.getUserID()会将我的FacebookAppID返回给我。

1 个答案:

答案 0 :(得分:0)

诀窍是修改库并添加一个promise。当它被解析时,对象被加载。:

angular.module('af.angular-socialshare', [])
.factory('$FB',['$window', '$q', function($window, $q){
  // data stored here exists only once per app
  var loaded = $q.defer();

  return {
    init: function(fbId, channelUrl){
      if(fbId){
        this.fbId = fbId;
        $window.fbAsyncInit = function() {
          FB.init({
            appId: fbId,
            channelUrl: channelUrl,
            status: true,
            xfbml: true
          });
          loaded.resolve($window.FB);
        };
        (function(d){
          var js,
          id = 'facebook-jssdk',
          ref = d.getElementsByTagName('script')[0];
          if (d.getElementById(id)) {
            return;
          }

          js = d.createElement('script');
          js.id = id;
          js.async = true;
          js.src = "//connect.facebook.net/en_US/all.js";

          ref.parentNode.insertBefore(js, ref);

        }(document));
      }
      else{
        throw("FB App Id Cannot be blank");
      }
    },
    getFB: function(){
      return loaded.promise;
    }

  };

}])

然后解析FB对象

$stateProvider
    .state('share',{
      url:'/share',
      templateUrl:'modules/Share/Share.html',
      controller: 'ShareCtrl',
      controllerAs:'shareCtrl',
      data: {
        auth: "LoggedIn"
      }
      ,
      resolve: {
        FB: ['$FB', function($FB){
          return $FB.getFB();
        }]
      }
    });