简体   繁体   中英

How to share the same config across multiple angular apps

I have the same config blocks for all the angular apps on my site, all in different files.

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');
  }
]);

Is there a standard way of abstracting this?

You could create another module say "myApp.common" or even "myApp.common.configs" and keep your common implementation in that module and include that module as a dependency in other modules which needs them.

Example:-

/*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');
  }
]);

and

//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']);
//...

On a side note, i would avoid storing my module in a global variable as in the example, instead prefer using module getter syntax instead whenever necessary. ex:- angular.module('app1').service(... , angular.module('app1').config(... etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM