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?

1 Answer 1

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

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

Comments

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.