Configuration file in AngularJS

What is the best way to create config file (Something like web config in .net), for storing urls, and other constants that may vary during the application deploy?


Solution 1:

Use the .constant() method:

angular.module('app').constant('MONGOLAB_CONFIG', {
  baseUrl: '/databases/',
  dbName: 'ascrum'
});

like in this example.

Then you can just inject it where you need the constants.

You can have different files defining different constants for development or production, and then use a tool like Grunt to use this or that file according to the environment.

Let's assume you have this kind of folder structure:

|-js/
|  |-app.js
|  |-anotherfile.js
|  |-...
|
|-env/
|  |-dev.js
|  |-prod.js
|
|-index.html

dev.js and prod.js defines the same .constant() service with different values. Then you can get the proper file to be concatenated with a gruntFile like that:

grunt.registerTask('default', ['concat']);

grunt.initConfig({
  env : process.env.NODE_ENV,
  src: {
    javascript: ['js/*.js'],
    config: ['env/<%= env %>.js']
  },
  concat: {
    javascript: {
      src:['<%= src.config %>', '<%= src.javascript %>'],
      dest:'myapp.js'
    }
  }
});

By running grunt you would get a myapp.js file containing the good constants.

Edit: with Gulp you can do it like this:

var paths = [
  'env/' + process.env.NODE_ENV + '.js',
  'js/**/*.js',
];

var stream = gulp.src(paths)
  .pipe(plugins.concat('main.js'))
  .pipe(gulp.dest('/output'));

Solution 2:

IMHO, I don't like handling config files with task runners. Cause you will need to rebuild your whole application just to change a line or two every time you need a different configuration.

Using the .config of angular is a good thing and I would do something like (borrowing from the example of the first answer)

angular.module('app').constant('MONGOLAB_CONFIG', {
  baseUrl: '/databases/',
  dbName: 'ascrum'
});

let's name this as app.config.js

And this will be linked in the .html right after the minified script like this

<script src="js/app-38e2ba1168.js"></script> //the application's minified script
<script src="/app.config.js"></script>

You can just then edit the app.config.js file without re running any tasks. So you can have different app.config.js files on different machines/environments without re building the app again and again

Solution 3:

Thinking outside the box, you don't really want to use .constant as it's tied to the application. Use a config that sits outside of the app and you have more control over env configs. I have provided a link below explains the pitfalls of have configs within the angular build itself.

(function hydrateConfiguration() {
"use strict";
var xhr = new XMLHttpRequest();
xhr.open("get", "conf.json", window);
xhr.onload = function () {
    var status = xhr.status;
    if (status === 200) {
        if (xhr.responseText) {
            var response = JSON.parse(xhr.responseText);
            window.ss_conf = response;
        }
    } else {

        console.error("messages: Could not load confguration -> ERROR ->", status);
    }
};

xhr.send() )());

Just a simple example where a external config file controls the state of the app and injects values outside in, instead of inside in.

https://www.jvandemo.com/how-to-configure-your-angularjs-application-using-environment-variables/