简体   繁体   中英

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

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.

您必须返回一个对象或函数或从工厂获取一个值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM