Injecting a service into another service in angularJS

AngularjsAngularjs Service

Angularjs Problem Overview


Is it possible to inject one service into another service in angularJS?

Angularjs Solutions


Solution 1 - Angularjs

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) {}]);

Solution 2 - Angularjs

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.

Solution 3 - Angularjs

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 );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSubtubesView Question on Stackoverflow
Solution 1 - AngularjsAlborzView Answer on Stackoverflow
Solution 2 - AngularjsPauli PriceView Answer on Stackoverflow
Solution 3 - AngularjsTiberiu OpreaView Answer on Stackoverflow