Why must a provider be defined before a config blo

2019-06-18 23:18发布

问题:

I have a module. It has a config block, a provider, and a constant defined. The config block references both the constant and the provider. I notice that my constant can be defined before or after my config block. The provider however must be defined BEFORE the config block or else I get an error.

Error: [$injector:modulerr] Failed to instantiate module loadOrder due to:
[$injector:unpr] Unknown provider: greetingsProvider

Here is some sample code:

var myModule = angular.module('loadOrder', []);

//if I define this after the config block, I get an error
angular.module('loadOrder').provider('greetings',[ function(){
    this.$get = [function(){
        return { greet: function(){ return "Hola"; } };
    }];
}]);

myModule.config(['$provide', 'greetingsProvider', 'planetName', function($provide, loadOrderProvider, planetName){
    $provide.value('someVals',[3,6,8]);
    console.log("Lets go to", planetName);
}]);

myModule.constant('planetName', 'Saturn');

Why is this? Why can't I define my provider after my config block?

回答1:

When you call provider, config or constant nothing happens immediately. The calls are registered, put in a queue and run during the initialization of the application.

The funny thing with constant is that it is put at the front of the queue. Thus it's available before config, no matter what.