How To Load Configuration Data On Startup With AngularJS

Posted By : Milind Ahuja | 22-Sep-2017

To load the configuration from server is the most natural way to run configuration before Angular startup in the same way in which Angular application makes multiple calls to the backend to get application data. This is however little bit different than that as the config data needs to be loaded before Angular, but the logic is the same.

 

 

We will achieve this by using Providers for the config object. Providers are not used that often in Angular applications, but they are also the most flexible - Value, Factory, Service and Constant are all just the syntactical sugar on top of Provider. For this case, we just know that the $get function is called by the injector when it needs to inject your object.

 

 

To know more about provider: https://docs.angularjs.org/guide/providers

 

angular.module('myApp').provider('configuration', function() {
  let configurationData;

  this.initialize = (data) => {
    configurationData = data;
  };

  this.$get = () => {
    return configurationData;
  };
});
 

 

 

Now what we need to do is manually bootstrap the Angular application. So instead of ng-app directive, we manually tel Angular to run the application.



angular.element(document).ready(() => {
  angular.bootstrap(document, ['myApp']);
});
 

 

 

The Final step is now to load configuration data and use the response in order to initialize the config provider.

 

angular.element(document).ready(() => {
  $.get('/configuration.json', (response) => {
    angular.module('plunker').config((configurationProvider) => {
      configurationProvider.initialize(response);
    });

    angular.bootstrap(document, ['plunker']);
  });
});
 

 

 

This ensures the configuration data to be loaded before the Angular application starts. SO the configuration data is present at the runtime.

 

 

Thanks

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..