Using a factory in config

1.8k Views Asked by At

I know the config phase runs before the services are available, but I have a situation where I need to use a myJsonDateTimeService to inject a $httpProvider.defaults.transformResponse like that:

angular.module('myJsonDateTimeInterceptor', ['myJsonDateTime'])
.config(function($httpProvider, myJsonDateTimeService){
    $httpProvider.defaults.transformResponse.push(function(responseData){
        myJsonDateTime.format(responseData); // Logic to change DateTime.
        return responseData;
    });
});

angular.module('myJsonDateTime', [])
.factory('myJsonDateTimeService', function(){
    var factory = {
        format: function(data) { ... }
    };
    return factory;    
});

The problem is that myJsonDateTimeService is used as service in other places and I would like to reuse the same logic in the config of my interceptor instead just replicate the format code.

I also don't know how to create a myJsonDateTimeProvider that could use the same logic of the factory.

Edit 1

As suggested, I rebuild this factory in a provider like that:

angular.module('myJsonDateTime', [])
.provider('myJsonDateTimeService', function(){
    var format = function(data) { ... };
    this.format = format;

    this.$get = function() {
        return { format: format };
    };
});

Not sure if that's the best way as the provider should be used to configure and not provide functions like formatting.

0

There are 0 best solutions below