John Nick
John Nick

Reputation: 25

Angularjs error when calling factory method

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?

Upvotes: 1

Views: 2291

Answers (1)

TGH
TGH

Reputation: 39258

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.

Upvotes: 4

Related Questions