0

In my project I have a couple of providers which I initialise during startup

angular.module('myApp', [])
    .config((barFooProvider, ....) => {
        barFooProvider.setAPIPath = '/a/b/c';
        ...
    });

As you can see I define an api-path here which is a string. But how can I set for example a factory ? Or is the only way to define the name of the service and later on use the $injector ?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

3 Answers3

1

You could use the $inject property annotation (docs) on the $get method of your provider:

myApp.provider('test', function() {

    this.setFactoryName = function(name) {
        this.$get.$inject = [name];
    };

    this.$get = function(factory) {
        return { 
            getMessageFromFactory: function() {
                return factory.msg;
            }
        };
    };

    // set default value
    this.setFactoryName('myFactory1');

});

then configure it this way:

myApp.config(function(testProvider){
    testProvider.setFactoryName('myFactory2');
});

This way the required factory will be injected to the $get method of your provider upon service instantiation.

Alexander Kravets
  • 4,245
  • 1
  • 16
  • 15
  • This is a nice solution. I already use the $injector like this: `this.$get = function($injector) { ... }`. In my case the dependencies are optional, meaning that you can set none or a couple of services. As far as I know this cannot be done with you solution, is that true? – Jeanluca Scaljeri Jun 13 '16 at 10:49
  • @JeanlucaScaljeri, yes, I guess so. – Alexander Kravets Jun 13 '16 at 10:57
0

You just can use Providers in Config Phase
In other words Providers are Configurable in AngularJs
May be this link would be helpfull

Community
  • 1
  • 1
nayeri
  • 175
  • 1
  • 7
0

providers are the only services that can be used in config phase!

app.provider('test', function() {

  // set default path
  var APIPath = 'a/b/c';

  function setAPIPath(path) {
       APIPath =  path;
  }

});


angular.module('app', []).config(function(testProvider) {
  // set path during config
  testProvider.setAPIPath('x/v/b');
});
Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69