简体   繁体   中英

Dynamic domain URL Rest factory AngularJS

I want change dynamic REST URL (for example if is stage or production) with a simple change in a server, but the URL don't change:

I have tried this:

.factory('Auth', ['$resource', 'Config', function($resource, Config) { 
    var URL = function(){
        var random = Math.floor((Math.random() * 100) + 1);
        window.localStorage.setItem("REST", "http://dynamic"+random+".com/");  
        return window.localStorage.getItem("REST");
    }
    return $resource(_url, {url:"url"}, {
        login: { method:'POST', url:  URL()},
    })
}])

And this

   // Generate random URL in the controller
   .factory('Auth', ['$resource', 'Config', function($resource, Config) { 
        var URL = window.localStorage.getItem("REST");
        return $resource(_url, {url:"url"}, {
            login: { method:'POST', url:  URL},
        })
    }])

But when I change the url ( I check this url in local storage and its change) the domain is the same anywhere unless that I reload the page, in this case works.

Thanks

You can do something like that:

Add a 2 new constant:

  .constant('HOST_CDN', {
    development: {
      api: 'http://YOUR_LOCAL_DOMAIN',
    },
    production: {
      api: 'http://YOUR_PRODUCTION_DOMAIN',
    }
  })
  .constant('ENV', 'development')

Create new service:

var domain = null;

(function getDomains() {
  domain = HOST_CDN[ENV];

  if (!domain) {
    throw 'Could not get domains';
  }

  domain.api   = domain.api.concat('/')
                           .replace(/\/\/$/, '/');
})();

return {
  api   : domain.api
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM