Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background processing notification for $http requests

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.

like image 475
tzortzik Avatar asked Dec 30 '15 14:12

tzortzik


1 Answers

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.

like image 89
scniro Avatar answered Sep 28 '22 05:09

scniro