Is it possible to inject one service into another service in angularJS?
Asked
Active
Viewed 6.2k times
3 Answers
118
Yes. follow the regular injection rule in angularjs.
app.service('service1', function(){});
//Inject service1 into service2
app.service('service2',function(service1){});
Thanks to @simon. It is better to use Array injection to avoid minifying problem.
app.service('service2',['service1', function(service1) {}]);

Alborz
- 6,843
- 3
- 22
- 37
-
20I suggest using the array injection way to avoid problem when you'll want to minify your scripts in the future: `['service1', function(service1) {}]` – Simon Belanger Jan 08 '14 at 19:32
-
2You can also use [`ngmin`](https://github.com/btford/ngmin) or associated grunt task. – John Ledbetter Jan 08 '14 at 19:38
-
if you wanted to access another method from the same service I presume you wouldn't want to inject the same service into the service; trying to call it using 'this' doesn't seem to work for me though, any thoughts on what is the best way of doing it? thanks! – timhc22 Nov 28 '14 at 18:35
-
Just wondering what if you inject 'service1' into 'service2', and also inject 'service2' into 'service1', what will happen then? What if one service's initialisation depending on the other service's initialisation? – Xinan Jul 10 '16 at 00:02
-
@Xinan in that case angularjs will throw error of cyclic dependcy. So avoid it and anyways that is not a good programming practice. – jitenagarwal19 Sep 10 '16 at 14:13
8
Yes. Like this (this is a provider, but same thing applies)
module.provider('SomeService', function () {
this.$get = ['$q','$db','$rootScope', '$timeout',
function($q,$db,$rootScope, $timeout) {
return reval;
}
});
In this example, $db
is a service declared elsewhere in the app and
injected into the provider's $get
function.

Pauli Price
- 4,187
- 3
- 34
- 62
5
In order to avoid any confusion, I think it is also worth mentioning that if you are using any other services (e.g. $http, $cookies, $state) in your childService, then you also need to explicitly declare them.
e.g.
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]);
}());
You can either declare the services you are using inside your child in an array and then they get injected automatically, or inject them separately with the $inject annotation:
childService.$inject = ["$http", "$cookies", "parentService"];
angular.module("app").service("childService ", childService );

Tiberiu Oprea
- 153
- 1
- 3
- 7