Getting cleaner code for multiple HTTP GET requests with angularjs

Issue

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?

Solution

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.

Answered By – Matt Way

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.