how to inject dependency into module.config(configFn) in angular

后端 未结 8 1113
轮回少年
轮回少年 2020-11-27 14:40

In Angular, we can inject $routeProvider to the config function

module.config(function ($routeProvider) {


});

I

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 15:01

    I don't have enough reputation to post a comment, but wanted to add to Mark's answer.

    You can register providers yourself. They are basically objects (or constructors) with a $get method. When you register a provider the standard version of it can be used like a service or factory, but a provider version can be used earlier. So a grumpy provider that is registered as

    angular.module('...', [])
        .provider('grumpy', GrumpyProviderObject)
    

    is then available in the config function as

        .config(['grumpyProvider', ..., function (grumpyProvider, ...) { ... }])
    

    and can be injected into controllers simply as

        .controller('myController', ['grumpy', ..., function (grumpy, ...) { ... }])
    

    The grumpy object that is injected into myController is simply the result of running the $get method on the GrumpyProviderObject. Note, the provider you register can also be a regular JavaScript constructor.

    Note: as per the comment by @Problematic, that the provider initialization (the call to angular.module().provider(…) must come before the config function to be available.

提交回复
热议问题