Problem: Large config()
The config of my AngularJS app is growing quite large. How would you refactor the following into separate files?
// 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 () {
...
});
});
Option 1. Multiple config()
s
I know that I can have multiple config()
s and place them in separate files like this:
// app.js
angular.module('myApp');
// routerConfiguration.js
angular.module('myApp')
.config(function($urlRouterProvider, $stateProvider) {
// Configure routing (uiRouter)
$urlRouterProvider.when('/site', '/site/welcome');
$stateProvider.state('main', ...
...
// httpInterceptorConfig.js
angular.module('myApp')
.config(function($httpProvider) {
// Configure http interceptors
$httpProvider.interceptors.push(function () {
...
});
});
What I do not like about this, is that in the original app.js, there is no way of getting an overview of what is run at startup.
Option 2. Inject something
I would prefer to do something like this, because it would be easier to see what is configured, directly in the app.js. However I know that this is not possible, since we cannot inject services into config()
.
Can I use providers to solve this? Is there a better way?
// 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 () {
...
}
};
});
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…