AngularJS global $http state ajax loader

这一生的挚爱 提交于 2019-12-14 03:42:52

问题


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.



来源:https://stackoverflow.com/questions/25604748/angularjs-global-http-state-ajax-loader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!