将大型AngularJS模块配置为独立文件

前端之家收集整理的这篇文章主要介绍了将大型AngularJS模块配置为独立文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:Large config()

我的AngularJS应用程序的配置正在增长非常大.如何将以下内容重构为单独的文件

// app.js
angular.module('myApp')
    .config(function($urlRouterProvider,$stateProvider,$httpProvider) {
        // Configure routing (uiRouter)
        $urlRouterProvider.when('/site','/site/welcome');
        $stateProvider.state('main',...
        ...

        // Configure http interceptors
        $httpProvider.interceptors.push(function () {              
            ...
        });
    });

选项1.多个config()s

我知道我可以有多个config()并将它们放在单独的文件中,如下所示:

// app.js
angular.module('myApp');

// routerConfiguration.js
angular.module('myApp')
    .config(function($urlRouterProvider,$stateProvider) {
        // Configure routing (uiRouter)
        $urlRouterProvider.when('/site',...
        ...

// httpInterceptorConfig.js
angular.module('myApp')
    .config(function($httpProvider) {
        // Configure http interceptors
        $httpProvider.interceptors.push(function () {              
            ...
        });
    });

我不喜欢这个,就是在原来的app.js中,没有办法了解启动时运行的内容.

选项2.注入东西

我更喜欢做这样的事情,因为直接在app.js中看到配置是比较容易的.但是我知道这是不可能的,因为我们无法将服务注入到config()中.

我可以用提供者来解决吗?有没有更好的办法?

// app.js
angular.module('myApp')
    .config(function(routerConfig,httpInterceptorConfig) {
        routerConfig.setup();
        httpInterceptorConfig.setup();
    });

// routerConfig.js
angular.module('myApp')
    .factory('routerConfig',function($urlRouterProvider,$stateProvider) {
        return {
            setup: function() {
                // Configure routing (uiRouter)
                $urlRouterProvider.when('/site','/site/welcome');
                $stateProvider.state('main',...
                ...
            }
        };
    });
});

// httpInterceptorConfig.js
angular.module('myApp')
    .factory('httpInterceptorConfig',function($httpProvider) {
        return {
            setup: function() {
                // Configure http interceptors
                $httpProvider.interceptors.push(function () {              
                ...
            }
        };
    });
});
您可以使用.constant作为.config中的依赖关系,因此您可以将配置声明用作手动组合根.例如:
angular.module('myApp')
    .config(function($urlRouterProvider,$httpProvider,routerConfig,httpInterceptorConfig) {
        routerConfig($urlRouterProvider,$stateProvider);
        httpInterceptorConfig($httpProvider);
    });

// routerConfig.js
angular.module('myApp')
    .constant('routerConfig',$stateProvider) {
        ...
    });

// httpInterceptorConfig.js
angular.module('myApp')
    .constant('httpInterceptorConfig',function($httpProvider) {          
        ...
    });

这种方法的缺点是您必须将所有配置依赖项注入到根配置函数中,然后手动将其注入到常量配置函数中.如果你有很多不同的配置功能,这可能会变得凌乱.它也可以看起来像你的配置函数具有注入Angular的依赖关系,但实际上你是手动进行的.每次添加新的配置功能时,您都需要确保记住手动连线.

我的首选方法是只有一个名为“config”的文件夹,其中只包含配置调用.

原文链接:https://www.f2er.com/angularjs/143167.html

猜你在找的Angularjs相关文章