1

I have been pondering over the 3 approaches to make HTTP GET REST calls with angularjs. They are $http, ngResource and restangular. I settled on $http because it is simplest and leads to the most readable code. However, my REST calls are getting complicated. I need to make nested HTTP GET requests and make sure that the requests are run in the correct sequence. The entire chain of HTTP GET requests stops if one fails.

The code will look something like this;

$http.get(url_get1).success(function(data, status, headers, config)
{
    $http.get(url_get2).success(function(data, status, headers, config)
    {
         $http.get(url_get3).success(function(data, status, headers, config)
         {
             //more action
         }
    }
}

If the chain of HTTP requests become long, the code becomes unreadable.

Would using ngResource or restangular make the code more readable and maintainable? Or are there other ways?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • If you need to make sure your calls are run in a particula sequence, then I would think hard about why. if you need data from one request to decide how to act on data from another, pull it into a variable – Nick Bailey Nov 04 '15 at 01:17
  • The variable content needs to be obtained from a HTTP GET first. So, I don't think I can avoid making the calls run in a particular sequence. – guagay_wk Nov 04 '15 at 01:18
  • Chain the promises instead of nesting. Makes the code far easier to read and maintain – charlietfl Nov 04 '15 at 01:20

2 Answers2

4

Your issue is not with get requests, but rather better ways of coding promises. What you need to do is create more modular functions that are able to deal with incoming data, and return what you need. For example:

function dataFromGetA(data){
    // modify your first get calls data here to the variable, or url you need for the next call
    return $http.get('http://someurl.com/' + data.someKey);
}

function dataFromGetB(data){
    return $http.get('http://someotherurl.com/' + data.somethingElse);
}

Once you create a set of these sorts of functions, they can be chained easily, like so:

$http.get(firstUrl)
    .then(dataFromGetA)
    .then(dataFromGetB);

Note here that I didn't simply chain $http calls together, as you mentioned that you needed the data from previous calls to work out the url for the next.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
3

$http.get() returns a promise.

$http.get(url_get1)
   .then($http.get(url_get2))
   .then($http.get(url_get3))

Have a read about promises

Additionally, check this answer: How to bundle Angular $http.get() calls?

Community
  • 1
  • 1
Said Kholov
  • 2,436
  • 1
  • 15
  • 22