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

后端 未结 8 1029
轮回少年
轮回少年 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:16

    You can manually call angular.injector to gain access to services which don't have dependencies during the .config() block of your app. If the service you created doesn't have any dependencies which need to be traversed, then you can probably use this:

    angular.module('myApp').config(function () {
        var myService = angular.injector(['ng']).get('myService');
    });
    

    This works for other simple services like $http as well:

    angular.module('myApp').config(function () {
        var http = angular.injector(['ng']).get('$http');
    });
    

    Note: Usually you shouldn't need to inject services during your config phase, it's better design to create a provider that allows for configuration. The docs say this functionality is exposed for cases where 3rd party libraries need to get access to the injector of an already-running Angular app.

    0 讨论(0)
  • 2020-11-27 15:17

    You can do it like this:

    (function() {
        'use strict';
    
        angular.module('name', name).config(config);
        // You can do this:
        config.$inject = ['$routeProvider', 'myService'];
    
        function config($routeProvider, myService) {
            // Or better to use this, but you need to use ng-annotate:
            /* ngInject */
    
        }
    });
    

    It is best practice that is described here

    0 讨论(0)
提交回复
热议问题