One of the things that I’m always being asked when I’m consulting about AngularJS is how to build a configuration service. The service requirements are to be able to load some configuration file and then to be able to use the configurations during runtime.
This post will show you a simple AngularJS configuration service which can be a good starting point for your own implementation.
Setting A Few Conventions
Before we start writing the service, you should think about some conventions. For example, where is the location of the configuration file? What format to use? and so on. In my implementation the configuration file is located in a config folder and I’m using the JSON format. Of course those aren’t restrictions and you can use your own favorite conventions. The following code is an example of a configuration file that I’ll use later in the example:
{
"config1": 15,
"config2": 20,
"config3": "config3"
}
Show Me Some Code
Now that we have our conventions, let’s see the service code:
(function () {
'use strict';
angular.
module('core').
factory('configurationService', configurationService);
configurationService.$inject = ['$http'];
function configurationService($http) {
var configurationObject = {};
function init() {
return $http.get('config/config.json').then(function (response) {
configurationObject = response.data;
});
}
function getConfigByKey(key) {
return configurationObject[key];
}
return {
init: init,
getConfigByKey: getConfigByKey
};
}
}());
As you can see the service is simple and it exposes two API functions:
- init() – to initialize the service and to set the configurationObject
- getConfigByKey(key) – enables to retrieve configurations during runtime
Make sure to run the init function only once when the application starts.
Using the Service
once you have the service, you can use it in your code. For example, the following code shows how to initialize the service and then retrieve a configuration:
(function () {
'use strict';
angular.
module("app").
controller("mainController", mainController);
mainController.$inject = ['configurationService'];
function mainController(config) {
function init() {
config.init().then(function() {
var config1 = config.getConfigByKey('config1');
/// Do whatever you like with the configuration
});
}
init();
}
}());
Summary
In the post I showed you how to write a simple AngularJS configuration service. This service can be a helpful starting point to much more sophisticated configuration service scenarios.