2014-07-19 66 views
0

我无法获得Angular.js依赖注入的自定义服务的工作。角度服务依赖注入不起作用

这是我的自定义工厂,它从自定义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; 

}]); 

但是,当我在主控制器中注入服务时,编译器指出myDataService未定义。

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

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


    $scope.books = myDataService.getData(); 

... 

这是为什么?

回答

1

你的工厂必须返回一些东西。这是一个的注入返回值:

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

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

更多关于Angular factories