background processing notification for $http requests
Asked Answered
F

2

6

I am looking for a way to "wrap" all the $http requests so that I can show a gif image whenever the application is doing some processing. I also want to use the same solution for other kind of background processing and not just $http.

The reason why I am asking is that I always have to set my processingIndicator to true and then switch back in my success function which is not elegant at all.

One potentially solution that I see is to use a function that takes a function as a parameter. This function will set the processingIndicator to true, call the function and then set processingIndicator back 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?

Later edit

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

Fireside answered 30/12, 2015 at 14:53 Comment(0)
C
2

Use an interceptor. Observe 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 inject centralized logic at various points during the http request life cycle, hooking into the supplied callbacks offered by the api. Crafting any reusable request logic you may need - just do so here. Check out the interceptors portion of the AngularJS $http docs for more information.

Centring answered 30/12, 2015 at 15:21 Comment(0)
R
0

I have successfully managed to use AngularOverlay for displaying a loading indicator while a http request is pending. Download the files and follow the instructions and it should work.

Rother answered 30/12, 2015 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.