Ken
Ken

Reputation: 3141

Fixing AngularJS error: Provider must return value from $get factory method

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;
    }
  }
});

Upvotes: 0

Views: 3846

Answers (2)

mohamedrias
mohamedrias

Reputation: 18576

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.

Upvotes: 2

Samir Das
Samir Das

Reputation: 1918

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

Upvotes: 0

Related Questions