Search code examples
angularjsangularjs-service

How to inject multiple angular services using $inject.get


Im having problem using $inject.get in angular js..

Let say i have angular services like this

app.service("serviceOne", function() { 
 this.dialogAlert = function() {
  return 'Message One'
 };
});

app.service("serviceTwo", function() { 
 this.dialogAlert = function() {
  return 'Message Two'
 };
});

app.service("serviceThree", function() { 
 this.dialogAlert = function() {
  return 'Message Three'
 };
});

And using the factory to dynamically call dialogAlert()

app.factory("alertService", function($window, $injector) {
 if ($window.servicesOne) {
   return $injector.get("serviceOne");
 } else {
   return $injector.get(["serviceTwo", "serviceThree"]);
 }
});

With this kind of codes, it gives me "unknown provider". Or is there any alternative solution for this? Thanks guys.


Solution

  • injector.get takes only one service name as argument, array is not supported, you may want to do return array of service instances by doing return ["serviceTwo", "serviceThree"].map($injector.get):-

    app.factory("alertService", function($window, $injector) {
      var service = ["serviceOne"];
      if (!$window.servicesOne) {
       service = ["serviceTwo", "serviceThree"]; 
      }
      return service.map($injector.get); //To be consistent send back this as well as array
    });
    

    So with this when you inject the alertService it will return an array of dependecy(ies).

    app.controller('MainCtrl', function($scope, alertService) {
     //  alertService will be array of dependecies.
      console.log(alertService.map(function(itm){return itm.dialogAlert()}));
    });
    

    Demo

    or return with a map:-

     app.factory("alertService", function($window, $injector) {
          var service = ["serviceOne"], 
              serviceObjs = {};
    
          if (!$window.servicesOne) {
           service = ["serviceTwo", "serviceThree"]; 
          }
    
          angular.forEach(service, function(itm){
            serviceObjs[itm] = $injector.get(itm);
           });
    
         return serviceObjs;
        });