4

I would like to include the Facebook javascript libraries in an Angular project such that all the facebook API calls (login, logout, etc) are encapsulated inside a service. But because of the async nature of the FB library my code seems overly verbose and I have several calls to $rootScope.apply() which I'm not sure is best practice.

Right now I have something like this:

app.factory('Facebook', function($rootScope, $window, $q){
  var FBdefer = $q.defer();
  var FBpromise = FBdefer.promise;
  $window.fbAsyncInit = function(){
    $rootScope.$apply(function(){
      FB.init(/* FB init code here*/);
      FBdefer.resolve(FB);
    }
  }

  var fb_service_api = {
    login: function(){
      var deferred = $q.defer();
      FBPromise.then(function(FB){
        FB.login(function(response){
          $rootScope.$apply(
            deferred.resolve(response)
          );
        });
      }
      return deferred.promise.
    }
  }

  return fb_service_api;
})

Looking for a good design pattern here that fits well with the angular framework.

sthomps
  • 4,480
  • 7
  • 35
  • 54

1 Answers1

0

I think that you may be able to solve this using Misko Hevery's approach here to delay loading of your controller(s) until the Facebook XHR calls have 'resolved'.

This seems to have solved all of my asynchronous data loading issues and will probably mean you can just delete your $apply() calls too.

Community
  • 1
  • 1
Matty J
  • 3,116
  • 32
  • 31
  • My issue with that approach is that the rest of my page doesn't need to wait for the fb library to load before the page starts to render. I was thinking the page could load and render the FB components asynchronously. – sthomps Mar 13 '13 at 15:16