Angular Tip: Using the XMLHttpRequest object

AngularJS logoNormally, an AngularJS application uses the $http service to make calls to back-end services. Sometimes, however, we would like to have access to the underlying XMLHttpRequest object. I can come up with a few use-cases, but the most prominent one is probably being able to track progress of a long request, such as a file upload. To do that, we need to register an event listener on the XMLHttpRequest object for the event that is “in progress.” Surprisingly enough, Angular’s $http service does not in any way expose the underlying XMLHttpRequest object. So, we have to get creative. Here is one way to do it…

The $http service’s config object allows us to add headers to the HTTP request via its “headers” property. That means that at some point $http has to set those headers on the XMLHttpRequest object it uses. The way to do that is to use XMLHttpRequest’s setRequestHeader method. So the idea is to override the setRequestHeader method on the XMLHttpRequest’s prototype and use a special header name to introduce a hook. Let’s begin with that and create a simple Angular module that performs the method substitution in its configuration phase:

Now, when we make an $http service call, we can add a header called “__XHR__” with a function value that will receive the XMLHttpRequest object as its only argument. For example, somewhere else in the application:

Hopefully, future versions of AngularJS will include some official way to access the low-level XMLHttpRequest object, even if limited, such as being able to register event listeners or translating the XMLHttpRequest events into Angular events. Until then, I am using the approach above in my apps.

4 thoughts on “Angular Tip: Using the XMLHttpRequest object

  1. AngularJS developers recognized the need for this and introduced $xhrFactory service in version 1.4.7. It makes things a little bit prettier now.

  2. Thank you for this tip, it saved me a lot of time. @Lev, how can be $xhrFactory used to handle ‘progress’ events? I am not quite getting the doc, which is not very descriptive.

Leave a Reply

Your email address will not be published. Required fields are marked *

By submitting this form, you accept the Mollom privacy policy.