Background Processing Notification for $ http Requests

I am looking for a way to "wrap" all $http requests so that I can display a gif image whenever the application does some processing. I also want to use the same solution to handle a different type, not just $http .

The reason I'm asking is because I always need to set my processingIndicator to true , and then go back to my success function, which is not elegant at all.

One potential solution I see is to use a function that takes a function as a parameter. This function will set processingIndicator to true , call the function, and then return processingIndicator to false.

 function processAjaxRequestSuccessFn(fooFn){ // display processing indicator fooFn(); // hide processing indicator } 

And then

 $http.get(...).then(processAjaxRequestSuccessFn, processAjaxRequestErrorFn) 

This solution is not very convenient, because every time I need to notify the user that something is happening, I need to use this function.

I am looking for a way to automate this process.

Any other ideas?

Edit later

Another idea that I have is to extend $http with my own get , post , etc. Or create a custom service that has similar behavior. But still not very elegant.

+6
source share
2 answers

Use an interceptor. Check out the following example ...

 app.factory('HttpInterceptor', ['$q', function ($q) { return { 'request': function (config) { /*...*/ return config || $q.when(config); // -- start request/show gif }, 'requestError': function (rejection) { /*...*/ return $q.reject(rejection); }, 'response': function (response) { // -- end request/hide gif /*...*/ return response || $q.when(response); }, 'responseError': function (rejection) { /*...*/ return $q.reject(rejection); } }; }]); 

 app.config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push('HttpInterceptor'); /*...*/ }]); 

Here you can enter centralized logic at different points throughout the life cycle of the HTTP request, connecting to the provided callbacks offered by the api. When creating any reusable request logic, you may need to - just do it here. For more information, check out the AngularJS $ http docs interceptor part.

+2
source

I was able to successfully use AngularOverlay to display a progress bar when the http request is pending. Download the files and follow the instructions and they should work.

0
source

All Articles