我的网站上的所有角度应用程序都有相同的配置块,所有这些都在不同的文件中.
app_1.config([ "$httpProvider", function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content'); } ]); app_2.config([ "$httpProvider", function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content'); } ]); app_3.config([ "$httpProvider", function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content'); } ]);
是否有标准的抽象方法?
您可以创建另一个模块"myApp.common"甚至"myApp.common.configs",并在该模块中保留您的通用实现,并将该模块作为依赖项包含在需要它们的其他模块中.
例:-
/*Create an app that has the common configuration used in your app clusters*/ angular.module('app.common', []).config([ "$httpProvider", function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content'); } ]);
和
//Include common module as well as a part of other dependencies your app may have var app_1 = angular.module('app1', ['app.common', 'somedep', ...]); var app_2 =angular.module('app2', ['app.common']); //...
另外,我会避免将模块存储在全局变量中,如示例所示,而是在需要时更喜欢使用模块getter语法.例如: - angular.module('app1').service(...
,angular.module('app1').config(...
等等.