0

When I use the code below, I am getting the following error:

Provider 'Login' must return a value from $get factory method.

I've reviewed the stackoverflow posts here and here, but can't figure out what I'm doing wrong.

myApp.factory('Login', function($location, $firebaseAuth, Ref, Auth) {
    var authData = Ref.getAuth();

   if (authData) {console.log('already logged in with ' + authData.uid)} else {

      return Auth.$authAnonymously({rememberMe: true}).then(redirect, showError);

      function redirect() {
      $location.path('/account');
    }

      function showError(err) {
      Login.err = err;
    }
  }
});
Community
  • 1
  • 1
Ken
  • 2,770
  • 11
  • 40
  • 61

2 Answers2

2

In terms of factory you must return an object. Since you're not returning anything, it means that other services/controllers can't use this service.

If you're just checking for Authentication, it must be inside your Auth service which must be an IIFE function. Which will check and redirect the user.

For example:

In either Auth/Ref service, create a IIFE

(function() {
var authData = Ref.getAuth();

   if (authData) {console.log('already logged in with ' + authData.uid)} else {

      return Auth.$authAnonymously({rememberMe: true}).then(redirect, showError);

      function redirect() {
      $location.path('/account');
    }

      function showError(err) {
      Login.err = err;
    }
  }
})();

Else insert the code inside init() method and call that in your service. SO this will run only once.

You must use service when you want to expose a singleton interface for other parts of your application to make use of.

mohamedrias
  • 17,260
  • 2
  • 33
  • 45
  • Thank you. What I'd like to do is check to see whether a user has already been authenticated. If not, then I want to authenticate. If already authenticated, then I don't really want to do anything. Are you suggesting that I wrap this in an IIFE function and change it to a service instead of a factory? – Ken Apr 02 '15 at 06:33
  • Updated it in my answer. – mohamedrias Apr 02 '15 at 06:40
  • Thank you, that makes sense. If i am already returning an object in the Auth service, can I still add the code above to that service? For example, can I first use `return $firebaseAuth(Ref);` before adding the rest of the code? I can't seem to include that additional line without running into other problems. – Ken Apr 02 '15 at 08:17
  • Yes, you can do that. This will be local to the Auth service and not going to affect the returned object. – mohamedrias Apr 02 '15 at 09:27
0

You must return an object or function or at leat a value from the factory

Samir Das
  • 1,798
  • 11
  • 18