在angularJS中将服务注入到另一个服务中

时间:2017-11-01 17:09:58

标签: angularjs

我有两项服务 CarServiceHomeService。我想将CarService注入HomeService,但它始终为空。在将CarService注入控制器时,它正在工作。我为什么做错了?

HomeService.$inject = ['carService']
function HomeService(carService){
    // here carService is null
}

修改

CarService.$inject = ['$localStorage'];
function CarService($localStorage) {


var myCarsPromise = getCars();

  var myLocalStorage = $localStorage.$default({
        cars: null 
    });

   function getCars(){
      return ['car'];
   }

   return {
        getCars
    };

}
export default CarService

1 个答案:

答案 0 :(得分:0)

服务通过Module API注册到模块。通常,您使用Module factory API注册服务

//Car Service
var myModule = angular.module('myModule', []);
myModule.factory('CarService', function() {
  //function body
});

要在Carservice中注入Homeservice,这就是方法

//Homeservice
var myModule = angular.module('myModule', []);
 myModule.factory('Homeservice',['Carservice', function(Carservice) {}]))