AngularJS global $http state ajax loader

2019-04-15 23:07发布

问题:

I have an AngularJS app, and need an ajax loader for every request done by the $http - is there a simple way to do this.

My solution now is to set $rootScope.loading = 1 everytime i call a $http, and on the success set $rootScope.loading = 0..

What is the "best practice" for this?

My code now looks like:

$rootScope.loading = 1;
$http({method : "POST", url:url, data: utils.params(data), headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function() {
    $rootScope.loading = 0;
});

回答1:

In this case will be better to use interceptor Anytime that we want to provide global functionality on all of our requests, such as authentication, error handling, etc., it’s useful to be able to provide the ability to intercept all requests before they pass to the server and back from the server.

angular.module('myApp')
.factory('myInterceptor',
function ($q,$rootScope) {
    var interceptor = {
        'request': function (config) {
         $rootScope.loading = 1;
        // Successful request method
            return config; // or $q.when(config);
        },
        'response': function (response) {
         $rootScope.loading = 0;
        // successful response
            return response; // or $q.when(config);
        },
        'requestError': function (rejection) {
            // an error happened on the request
            // if we can recover from the error
            // we can return a new request
            // or promise
            return response; // or new promise
                // Otherwise, we can reject the next
                // by returning a rejection
                // return $q.reject(rejection);
        },
        'responseError': function (rejection) {
            // an error happened on the request
            // if we can recover from the error
            // we can return a new response
            // or promise
            return rejection; // or new promise
                // Otherwise, we can reject the next
                // by returning a rejection
                // return $q.reject(rejection);
        }
    };
    return interceptor;
});

and register it to the config

angular.module('myApp')
  .config(function($httpProvider) {
   $httpProvider.interceptors.push('myInterceptor');
});

example from ng-book



回答2:

Use an http interceptor in order to intercept all your $http requests\responses and perform logic in them.

Here's an example of creating a custom one.
Here's an example of a ready module.