I'm still learning AngularJS, and have a question regarding their flavor of dependency injection.  For example purposes, say I have a DataProcessor service which has a processData method that takes in a uri parameter and it needs to read that data (which may be xml, json, etc.) and then perform some actions on it.  The DataProcessor constructor takes in an implementation of a DataReader interface that knows how to read a certain file type.  Here are some example services of what I'm talking about:
// implementations of the DataReader interface
myApp.service('XmlDataReader', function() {
    this.readData = function(uri) {
        // read xml data from uri
    }
}]);
myApp.service('JsonDataReader', function() {
    this.readData = function(uri) {
        // read json data from uri
    }
}]);
// data processing service that takes in an implementation of a DataReader
myApp.service('DataProcessor', ['DataReader', function(DataReader) {
    this.processData = function(uri) {
        var readData = DataReader.readData(uri);
        // process data and return it
    }
}]);
From a typical dependency injection perspective, a specific type of DataReader could be passed into the DataProcessor and used like so:
var dataProcessor = new DataProcessor(new JsonDataReader());
var processedData = dataProcessor.processData('dataz.json');
What is the AngularJS way of doing this?
Do something like this:
myApp.service('DataProcessor', ['$injector', 'valueRecipeOfTheServicename', function($injector, valueRecipeOfTheServicename) {
    this.processData = function(uri) {
        var service = $injector.get(valueRecipeOfTheServicename);
        // process data and return it
    }
}]);
$injetcor.get() retrieves a service
Based on Noypi Gilas answer, I am initiating the controller with the name of the service and retrieving it via $injetcor.get():
myApp.service('DataProcessor', ['$injector', function($injector) {
    var service;
    $scope.init = function (serviceName) {
        service = $injector.get(serviceName);
    }
    this.processData = function(uri) {
        // use the service ...
    }
}]);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With