Sumit Deshpande Sumit Deshpande - 7 months ago 12
Javascript Question

How to dynamically change $http service URL in AngularJS?

I am using angular $http service to get/post the data. Currently all the services using common URL to retrieve the data. Now I have requirement where I want to switch between the 2 URLs based on specific condition. So what will be the best approach to implement this functionality seamlessly without making many changes into existing service code?

Note - I don't want to write identification logic at each services.

I created sample example to explain the problem. In example currently I am using TEST_FILE1 from constant service as URL but i want to switch between TEST_FILE1 and TEST_FILE2 based on specific condition say based on random number returned from randomNumberService. Sample Example - Sample Plunkar Any help appreciated!

app.constant('RESOURCES', (function() {
return {
TEST_FILE1: 'test.json',
TEST_FILE2: 'test1.json',
}
})());

app.factory('myService', function($http, RESOURCES) {
return {
async: function() {
return $http.get(RESOURCES.TEST_FILE1); //1. this returns promise
}
};
});

app.factory('randomNumberService', function() {
return {
getRandomNumber: function() {
return Math.floor((Math.random() * 6) + 1);
}
}
});

GG. GG.
Answer

To not repeat the URL choice logic everywhere, then you have to move it in an other factory.

app.factory('identification', function (RESOURCES, randomNumberService) {
    return {
        getUrl: function () {
            var randomNumber = randomNumberService.getRandomNumber();
            var url = randomNumber > xxx ? RESOURCES.TEST_FILE1 : RESOURCES.TEST_FILE2;
            return url;
        }
    };
});

app.factory('myService', function($http, identification) {
  return {
    async: function() {
      return $http.get(identification.getUrl());
    }
  };
});

app.factory('randomNumberService', function() {
  return {
    getRandomNumber: function() {
      return Math.floor((Math.random() * 6) + 1);
    }
  }
});