是否可以在angularJS中将一项服务注入另一项服务?
是.像这样(这是一个提供者,但同样适用)
module.provider('SomeService', function () { this.$get = ['$q','$db','$rootScope', '$timeout', function($q,$db,$rootScope, $timeout) { return reval; } });
在此示例中,$db
是在应用程序的其他位置声明并注入提供程序$get
函数的服务.
为了避免混淆,我认为值得一提的是,如果您在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]); }());
您可以在数组中声明您在子项内使用的服务,然后自动注入它们,或者使用$ inject注释单独注入它们:
childService.$inject = ["$http", "$cookies", "parentService"]; angular.module("app").service("childService ", childService );
是.遵循angularjs中的常规注射规则.
app.service('service1', function(){}); //Inject service1 into service2 app.service('service2',function(service1){});
感谢@simon.最好使用Array注入来避免缩小问题.
app.service('service2',['service1', function(service1) {}]);