0

I cannot get Angular.js dependency injection of a custom service to work.

Here is my custom factory, which does receive data from the custom api.

myApp.factory('myDataService', ['$http', function($http){

   myDataService.getData = function() {

    $http.get('/api/reviews')
    .success(function(data, status, headers, config) {

        console.log("Data received");
        return data;

    })
    .error(function(data, status, headers, config) {
        console.error("No data received");
    })

};

return myDataService;

}]);

But when I inject the service in the main controller I the compiler states that myDataService is not defined.

var myApp = angular.module('myApp', []);

myApp.controller('ListCtrl', ['$scope', 'myDataService', function($scope, myDataService) {


    $scope.books = myDataService.getData();

...

Why is that?

user3025970
  • 75
  • 1
  • 2
  • 6

1 Answers1

1

Your factory has to return something. It's the return value that's injected:

myApp.factory('myDataService', ['$http', function($http){

   var myDataService = {};
   myDataService.getData = function() {
        ...
  })
    return myDataService;
};

More on Angular factories

Community
  • 1
  • 1
Michael Kang
  • 52,003
  • 16
  • 103
  • 135