如何在多个角度应用程序之间共享相同的配置

How to share the same config across multiple angular apps

本文关键字:共享 之间 配置 应用程序      更新时间:2023-09-26

我网站上所有角度应用程序都有相同的配置块,都在不同的文件中。

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(...等。