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

后端 未结 4 1143
耶瑟儿~
耶瑟儿~ 2020-12-10 05:18

I have a development and production environment in which my URL\'s differ:

production:

www.exmaple.com/page

development:

d

4条回答
  •  遥遥无期
    2020-12-10 05:54

    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, Safari
    xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "config.xml", false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    

    let your config.xml have such a field

    
      
    http://dev/ur/
    
    

    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!

提交回复
热议问题