Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs Post-Receive Hook or Similar?

Tags:

angularjs

Is there a way to call a function every time after a response is returned from a server without explicitly calling it after in the callback?

The main purpose is that I do have a generic error handler service that I call in every request's callback and I want to specify it somewhere and it shall be called automatically.

like image 258
Umur Kontacı Avatar asked Aug 08 '12 11:08

Umur Kontacı


1 Answers

I gave Gloopy a +1 on solution, however, that other post he references does DOM manipulation in the function defined in the config and the interceptor. Instead, I moved the logic for starting spinner into the top of the intercepter and I use a variable in the $rootScope to control the hide/show of the spinner. It seems to work pretty well and I believe is much more testable.

<img ng-show="polling" src="images/ajax-loader.gif">
angular.module('myApp.services', ['ngResource']).
.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
    var spinnerFunction = function (data, headersGetter) {
        return data;
    };
    $httpProvider.defaults.transformRequest.push(spinnerFunction);
})
//register the interceptor as a service, intercepts ALL angular ajax http calls
.factory('myHttpInterceptor', function ($q, $window, $rootScope) {
    return function (promise) {
        $rootScope.polling = true;
        return promise.then(function (response) {
            $rootScope.polling = false;
            return response;
        }, function (response) {
            $rootScope.polling = false;
            $rootScope.network_error = true;
            return $q.reject(response);
        });
    };
})
// other code left out
like image 68
Dan Doyon Avatar answered Oct 12 '22 12:10

Dan Doyon