Angular JS: why the difference between module.config injection and controller injection?

北城余情 提交于 2019-12-03 15:24:34

A provider is responsible for creating instances. In your example, you created a provider explicitly, but the truth is that every service has a provider, even if it's created automatically for it. [module].service() and [module].factory() are just shortcuts for [module].provider().

[module].config() is run during provider registrations and configurations so you get a change to access providers and do stuff with them. It's a place for configuration of things, hence the name.

From the documentation (http://docs.angularjs.org/guide/module):

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Controllers, in the other hand, are instantiated AFTER services have been configured, so you're not supposed to mess with providers anymore. Everything has already been configured. You're ready to get their products now. In this phase, the injector just can't inject providers anymore, just instances (services) created by them.

If you register a service myService...

myModule.service('myService', function() {
    // this is your service constructor
});

then you can access its provider, myServiceProvider, in a config function...

myModule.config(function(myServiceProvider) {
    // to stuff with your provider here
});

but by the time controllers are being instantiated, you're supposed to ask for services, not their providers, so this will not work...

myModule.controller(function(myServiceProvider) {
    ...
});

whereas this will be fine...

myModule.controller(function(myService) {
    ...
});

If you're finding yourself needing to do configuration in a controller, you should stop and rethink the place of responsibilities.

Lior

From the Angular mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. I decided to put it in its own question here

the specific answer is: it is so by design, to allow configuration of the provider at config time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!