0
votes

I am building an angular+firebase app with user authentication (with angularfire 0.8).

I need to use onAuth() auth event handler, since I will provide multiple authentication paths, included social, and want to avoid code duplication. Inside onAuth callback, I need to reset location.path to '/'.

Usually everything works nicely, but, if app is loaded on an already authenticated session (<F5>, for example), on $scope.$apply() I get "Error: [$rootScope:inprog] $apply already in progress"
(if I don't use $scope.$apply(), location path is not applyed to scope, and no page change happens).

I suspect I make some stupid mistake, but can't identify it...

This is my workflow:

app.controller('AuthCtrl', function ($scope, $rootScope, User) {
  var ref = new Firebase(MY_FIREBASE_URL);
  $scope.init = function () {
    $scope.users = [];  
    User.all.$bindTo($scope, 'users').then(function () {
      console.info('$scope.users bound:', $scope.users);
    });
  };
  $scope.login = function () {
    ref.authWithPassword({
      email: $scope.user.email,
      password: $scope.user.password,
    }, function(err) {
      if (err) {
        console.error('Error during authentication:', err);
      }
    });
  };

  ref.onAuth(function(authData) {
    if (authData) {
      console.info('Login success');
      var $rootScope.currentUser = $scope.users[authData.uid];
      $location.path('/');
      $scope.$apply();
    } else {
      console.info('Logout success');
    }
  });
};

app.factory('User', function ($firebase) {
  var ref = $firebase(new Firebase(MY_FIREBASE_URL + 'users'));
  return {
    all: ref.$asObject()
  };
});
1
Hey MarcoS, I see you had the similar problem to mine. Would you please care to take a look at my question: stackoverflow.com/questions/31872935/… - Nikola
I did, but you are on a quite different environment then me (Ionic / Angular+Firebase)... And, sorry, I'm not using Angular since some months (just waiting for 2.0... :-), so I really can't help you... :-( - MarcoS
Thanks for reply. I managed to get the resolution to this issue. - Nikola

1 Answers

1
votes

Just as a reference, I want to post the solution I found, and I'm currently adopting:

 $scope.init = function () {
    $scope.params = $routeParams;
    $scope.debug = CFG.DEBUG;
    $scope.lastBuildDate = lastBuildDate;
    $scope.error = null;
    $scope.info = null;

    $scope.users = [];

    User.all.$bindTo($scope, 'users').then(function () {
      // watch authentication events
      refAuth.onAuth(function(authData) {
        $scope.auth(authData);
      });
    });

    ...
  };
  ...

I.e., it was enough to move the watch on authentication events inside the callback to bindTo on users object from Firebase.