Setup Different Environment in AngularJS

Posted By : Himanshu Goyal | 27-May-2016

Intro: In Every application there lot url used in many places like the backend .So we need to setup the different enviorment in angularJS application also rather then hardcode the url. grunt-ng-constant is module in grunt which help to create the different enviorment in the application.You just need to inject the angularjs module in your application.use these constant everywhere in application.

Steps:  These are   essential setup to do every angularjs application.

  1. Setup the node-js and npm
  2. Setup the grunt 
  3. run npm install grunt-ng-constant // this grunt module used
  4. grunt buildenv:production //this is grunt command used to build production env.

Code:

'use strict';
/*
@author
Himanshu Goyal
*/
module.exports = function (grunt) {

    /*  */
    grunt.loadNpmTasks('grunt-ng-constant');

    grunt.initConfig({
        ngconstant: {
            development: {
                options: {
                    dest: './config/config.constant.js',
                    space: ' ',
                    wrap: '\n\n {%= __ngModule %}',
                    name: 'UrlConfiguration',
                },
                constants: {
                    $enviornment: require('./config/development.json')
                }
            },
            staging: {
                options: {
                    dest: './config/config.constant.js',
                    space: ' ',
                    wrap: '\n\n {%= __ngModule %}',
                    name: 'UrlConfiguration',
                },
                constants: {
                    $enviornment: require('./config/staging.json')
                }
            },
            production: {
                options: {
                    dest: './config/config.constant.js',
                    space: ' ',
                    wrap: '\n\n {%= __ngModule %}',
                    name: 'UrlConfiguration',
                },
                constants: {
                    $enviornment: require('./config/production.json')
                }
            }
        }
    });

    grunt.registerTask('buildenv', function (n) {
        console.log("you are building  " + n);
        grunt.task.run('ngconstant:' + n)
    })
};
//file generate after grunt command run

 angular.module('UrlConfiguration', [])
.constant('$enviornment', {name:'production',url:'http://localhost:8080/'});

//sample file of production url
{
    "name":"production",
    "url":"http://localhost:8080/"
}



THANKS

About Author

Author Image
Himanshu Goyal

Himanshu is a bright Java ,Mean stack developer and have good knowledge of Hibernate, Spring,FFmepg,Neo4j JSON, Jquery, NODE.JS .His hobbies are learning new things, fitness .

Request for Proposal

Name is required

Comment is required

Sending message..