Building a Simple AngularJS Configuration Service

龙 宇 2016-7-27 微信营销 0 0

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 theinitfunction 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.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

原文地址:http://www.77169.com/classical/HTML/203331.shtm

转载请注明来自华盟网,本文标题:《Building a Simple AngularJS Configuration Service》

喜欢 (0) 发布评论
发表评论