Samuel Samuel - 10 months ago 58
AngularJS Question

Batching / combing requests in AngularJS

I have an AngularJS application that has a lot of directives which are populated from nested nodes in AJAX requests. For example I might get a response like:

name: "Blog post title",
comment_ids: [1, 2, 3]

Currently in my controller, I will make a request to load data for each of the child nodes comments and populate them onto the scope. Something like:

_.each(comment_ids, function(id) {
scope.comment_data[id] = $http.get(id); // psuedocode for the $get

I then use the data on the page like:

<comment data="comment_data.1"></comment>

This works great but I'm thinking about converting my directives to take an id instead of an object and to handle loading the data themselves. The problem I face is that I might get multiple requests to the same endpoint if the same directive is present on the page multiple times, e.g.

<comment id="1"></comment>
<comment id="1"></comment>
<comment id="1"></comment>

This is going to result in three calls to the comments endpoint. Given this:

Will the browser batch multiple calls to the same HTTP endpoint into one request if it occurs in small space of time, or should I write an interceptor to handle doing it myself?

Answer Source

This problem is now solved quite elegantly with: