maxmantz
maxmantz

Reputation: 712

Configuring shared services across multiple modules in AngularJS

My app is following John Papa's styleguide for AngularJS applications:

The styleguide emphasizes using a strongly modular approach to the design of the app. My question is about multiple configurations and their effect on shared services.

Suppose I have a main module like this:

angular.module("app", ["app.feature1"])
  .config(function() {
    // do some configuration here
    console.log("app configured");
  });

And a feature module that configures a shared angular service, let's say the $http service:

angular.module("app.feature1", [])
  .config(function($http) {
  // configure the $http service
  console.log("feature1 configured");
}); 

Is my understanding correct, that the configuration by "feature1" will carry over to the main module, since the $http service is a singleton and therefore shared across modules? Or do I have to configure the $http service in the main module instead, because each module has it's own $http service instance?

Edit: I can confirm that dependency configs are carried over and are executed first. See David's jsfiddle example.

Upvotes: 2

Views: 471

Answers (1)

David L
David L

Reputation: 33833

As a matter of best practice, you should configure services as early as possible, which is typically your main module (the app root), and preferably only once to avoid overlapping changes.

Since $http is a singleton (as you mentioned), any changes via configuration will be propagated throughout the application every time you inject $http.

It's also worth mentioning that configuration to services is First In First Out, meaning that if you have two configuration changes, the last-accessed configuration will be the one that is persisted to the service since the previous configuration will be overwritten if they are changing identical components of the service.

In your case, yes, the change to $http in your module will be extended to your main application and any other modules using $http.

Finally, in light of the comments, child dependency configs are resolved before parent configs, as demonstrated by this simple fiddle:

http://jsfiddle.net/maqzo6fv/

HTML:

<div ng-app="app"></div>

JS:

angular.module("app", ["app.feature1"])
    .config(function() {
        alert('main config');
});

angular.module("app.feature1", [])
    .config(function() {
        alert('child config');
}); 

The child config will call alert before main on every load.

Upvotes: 1

Related Questions