【发布时间】:2014-01-27 02:11:24
【问题描述】:
是否可以在 angularJS 中将一项服务注入到另一项服务中?
【问题讨论】:
标签: angularjs angularjs-service
是否可以在 angularJS 中将一项服务注入到另一项服务中?
【问题讨论】:
标签: angularjs angularjs-service
为了避免任何混淆,我认为还值得一提的是,如果您在 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。最好使用数组注入来避免缩小问题。
app.service('service2',['service1', function(service1) {}]);
【讨论】:
['service1', function(service1) {}]
ngmin或者相关的grunt task。
是的。像这样(这是一个提供者,但同样适用)
module.provider('SomeService', function () {
this.$get = ['$q','$db','$rootScope', '$timeout',
function($q,$db,$rootScope, $timeout) {
return reval;
}
});
在此示例中,$db 是在应用程序的其他位置声明的服务,并且
注入到提供者的$get函数中。
【讨论】: