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

Edg*_*nez 81 angularjs angularjs-service

是否可以在angularJS中将一项服务注入另一项服务?

Alb*_*orz 115

是.遵循angularjs中的常规注射规则.

app.service('service1', function(){});

//Inject service1 into service2
app.service('service2',function(service1){});
Run Code Online (Sandbox Code Playgroud)

感谢@simon.最好使用Array注入来避免缩小问题.

  app.service('service2',['service1', function(service1) {}]);
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用数组注入方法以避免在将来缩小脚本时出现问题:`['service1',function(service1){}]` (20认同)
  • 您还可以使用[`ngmin`](https://github.com/btford/ngmin)或相关的grunt任务. (2认同)

Pau*_*ice 8

是.像这样(这是一个提供者,但同样适用)

    module.provider('SomeService', function () {


    this.$get = ['$q','$db','$rootScope', '$timeout', 
                function($q,$db,$rootScope, $timeout) {
          return reval;
    }
    });
Run Code Online (Sandbox Code Playgroud)

在此示例中,$db是在应用程序的其他位置声明并注入提供程序$get函数的服务.


Tib*_*rea 5

为了避免混淆,我认为值得一提的是,如果您在childService中使用任何其他服务(例如$ http,$ cookies,$ state),那么您还需要明确声明它们.

例如

function() {
  var childService = function($http, $cookies, parentService) {

  // Methods inherited
  this.method1Inherited = parentService.method1();
  this.method2Inherited = parentService.method2();

  // You can always add more functionality to your child service

  angular.module("app").service("childService", ["$http", "$cookies", "parentService", childService]);

}());
Run Code Online (Sandbox Code Playgroud)

您可以在数组中声明您在子项内使用的服务,然后自动注入它们,或者使用$ inject注释单独注入它们:

childService.$inject = ["$http", "$cookies", "parentService"]; 
angular.module("app").service("childService ", childService );
Run Code Online (Sandbox Code Playgroud)