user3025970
user3025970

Reputation: 75

Angular Service Dependency Injection Doesn't Work

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?

Upvotes: 0

Views: 673

Answers (1)

Michael Kang
Michael Kang

Reputation: 52847

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

Upvotes: 1

Related Questions