How to set AngularjJS base URL dynamically based on fetched environment variable? How to set AngularjJS base URL dynamically based on fetched environment variable? angularjs angularjs

How to set AngularjJS base URL dynamically based on fetched environment variable?


I personnaly do this kind of stuff with grunt.

When I run my angular-app I have multiple tasks :

> grunt run --target=dev> grunt run --target=prod> grunt build --target=dev> grunt build --target=prod> etc...

Then grunt do strings replacement with the help of the grunt-preprocess module :

my constants.tpl.js file gets parsed :

[...]baseUrl:           '/* @echo ENV_WS_URL */',[...]

and the url is populated.

There are endless possibilities (string replacements, file copy, etc).

Doing it with grunt ensure that dev config files do not go in production for example..

I can put more details if you're interested but I only wanted to show you a different approach.

edit gruntFile example :

'use strict';module.exports = function(grunt) {    /**     * Retrieving current target     */    var target = grunt.option('target') || 'dev';    var availableTargets = [        'dev',        'prod'    ];    /**     * Load environment-specific variables     */    var envConfig = grunt.file.readJSON('conf.' + target + '.json');    /**     * This is the configuration object Grunt uses to give each plugin its     * instructions.     */    grunt.initConfig({        env: envConfig,               /*****************************************/        /* Build files to a specific env or mode */        /*****************************************/        preprocess: {            options: {                context: {                    ENV_WS_URL: '<%= env.wsUrl %>'                }            },            constants: {                src: 'constants.tpl.js',                dest: 'constants.js'            }        },        karma: {            unit: {                configFile: '<%= src.karma %>',                autoWatch: false,                singleRun: true            },            watch: {                configFile: '<%= src.karma %>',                autoWatch: true,                singleRun: false            }        }    });    /****************/    /* Plugins load */    /****************/    grunt.loadNpmTasks('grunt-preprocess');    /*******************/    /* Available tasks */    /*******************/    grunt.registerTask('run', 'Run task, launch web server for dev part', ['preprocess:constants']);};

Now, the command :

> grunt run --target=dev

will create a new file with an url


asumming you created a service that gets configuration object from server

app.run(function($rootScope, yourService){       yourService.fetchConfig(function(config){        $rootScope.baseUrl = config.baseUrl;   })});

markup

<html ng-app="yourApp"><head>   <base ng-href="{{baseUrl}}">   ......

note

  • If your service uses $http or $resource you should be fine
  • If instead you use jQuery ajax calls you should run $rootScope.$apply() after setting variables to the scope.


using base urls might not be the best thing because it might also screw up the functioning of the anchor tags and might lead to un wanted navigation. The approach that you have to read the configuration from an XML file is perfect and this is what i did:

1.Before initializing your angular app read a variable from your config file:

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp = new XMLHttpRequest();}else {// code for IE6, IE5xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}xmlhttp.open("GET", "config.xml", false);xmlhttp.send();xmlDoc = xmlhttp.responseXML;

let your config.xml have such a field

<?xml version="1.0" encoding="utf-8" ?><config>  <url>http://dev/ur/</url></config>

2.now inject a constant in your app for this i was guided by Eddiec and Cd

var myApp= angular.module("App", ["ui.router"]).constant('BASE_URL',      xmlDoc.getElementsByTagName("url")[0].childNodes[0].nodeValue);

3.you can use BASE_URL anywhere across your app you need to inject it this is how i used it to avoid hard coded paths in ui.router.js

var routeResolver = function ($stateProvider, $urlRouterProvider,BASE_URL){  $stateProvider    .state('home', {        url: "/Home",        views: {            "main-view": {                templateUrl: BASE_URL+"/views/Home.htm",                controller: "homeCtrl",                resolve: {                }            }        }    })}myApp.config(routeResolver);

hope it helps cheers!