1

I am new to angularjs. I am trying to call a function in a factory but I am getting the below error,

Error: [$injector:undef] Provider 'todoStorage' must return a value from $get factory method.

This is my factory,

todomvc.factory('todoStorage', function ($q,$http) {
var STORAGE_ID = 'todos-angularjs-perf';

 function get(){
            var promise = $q.defer();

            $http.get('http://localhost/test.php').success(function(data){
                    promise.resolve(data);
            });

            return promise.promise;
        }

});

And this is how I call the function,

var todos = $scope.todos = todoStorage.get();

What exactly is happening and why this error coming up?

1 Answer 1

4
todomvc.factory('todoStorage', function ($q,$http) {
var STORAGE_ID = 'todos-angularjs-perf';


 function get(){

   return $http.get('http://localhost/test.php');
 }

 return{get:get};

});

//call the service like this
todoStorage.get().then(function(res){
  $scope.todos = res.data;
});

Your code is not returning the actual service factory. Since you are using factory you have return some JavaScript object pointing to your internal function. Otherwise it's not a valid factory, and your external code will have no way of getting to the internal get function.

Sign up to request clarification or add additional context in comments.

4 Comments

The error is resolved, but why I am not getting the data. The promise is returning null. Does defer make the call synchronous?
I recommend that you resolve the promise on the calling side instead of inside the service. Also, based on the implementation of $q, promises will never behave synchronously, even if the promise is resolved immediately.
I would not create a new promise here. It's easier to just return the original promise generated by $http.
I tried to access the data after calling the service as u mentioned. But only the promise object is getting printed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.