Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dependency injection swap implementation

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?

like image 311
chinabuffet Avatar asked Dec 19 '13 14:12

chinabuffet


2 Answers

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

like image 133
Noypi Gilas Avatar answered Oct 25 '22 08:10

Noypi Gilas


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 ...
    }
}]);
like image 27
Alvis Avatar answered Oct 25 '22 10:10

Alvis