0

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);
    }
  }
});

1 Answer 1

1

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);
    }
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer! But I specifically mentioned that I am not looking URL identification logic at the individual service level in that case I have to mimic same logic into all my services.
Thanks CG! Appreciate!
Your welcome! Would appreciate if you could upvote the answer. :)
Please edit your answer so that identification will have dependency of RESOURCES and remove RESOURCES from myService to make it correct...Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.