user1411469
user1411469

Reputation: 379

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?

Upvotes: 2

Views: 986

Answers (1)

PSL
PSL

Reputation: 123739

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.

Upvotes: 6

Related Questions