Search code examples
angularjsangular-providers

In Angular, why am I forced to declare the provider before the config?


Why am I forced to declare the provider before the config function that will uses it?

In others words, this code works:

angular.module('app')
  .provider('testService', function() {
    // ...
  })
  .config(function(testServiceProvider) {
    // ...
  });

but not this one (got an [$injector:unpr] Unknown provider: testServiceProvider):

angular.module('app')
  .config(function(testServiceProvider) {
    // ...
  })
  .provider('testService', function() {
    // ...
  });

(in my real code, these 2 blocks are defined in separate files, and thus the order of loading these files really matters)

My understanding was that when I call module('app').config(...) and module('app').provider(...), the code is not executed immediately, but when the Angular application is bootstraped, and thus, that's the role of Angular to execute the differents code in correct order (i.e. the provider code and then the config code).

Thanks

ps1: I already saw this question, which is quite the same but the answer was more about suggestion or guessing...

ps2: I'm still working with Angular 1.2, maybe things changed with Angular 1.3 - 1.4?


Solution

  • I've tested on several Angular versions, and it appears to be a "bug" in 1.2.x version. Starting from 1.3.0 version, the order of the definition of the provider and config is not important.

    test code:

    angular.module('myApp',[])
      .provider('testService', function() {
        console.log('.. service');
        this.$get = function () {
          return {};
        };
      })
      .config(function(testServiceProvider) {
        console.log('.. config');
      });