AngularJS全局$ http状态ajax加载器

pkd*_*dkk 1 angularjs angularjs-scope angular-http

我有一个AngularJS应用程序,需要一个ajax加载器来处理$ http所做的每个请求 - 有一个简单的方法来做到这一点.

我现在的解决方案是每次调用$ http时设置$ rootScope.loading = 1,并在成功设置$ rootScope.loading = 0 ..

这是什么"最佳实践"?

我的代码现在看起来像:

$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;
});
Run Code Online (Sandbox Code Playgroud)

Nar*_*yan 9

在这种情况下,最好使用拦截器 Anytime我们想要在我们的所有请求上提供全局功能,例如身份验证,错误处理等,能够提供在传递给所有请求之前拦截它们的能力是很有用的.服务器并从服务器返回.

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;
});
Run Code Online (Sandbox Code Playgroud)

并将其注册到配置

angular.module('myApp')
  .config(function($httpProvider) {
   $httpProvider.interceptors.push('myInterceptor');
});
Run Code Online (Sandbox Code Playgroud)

来自ng-book的例子