如何使http拦截器微调器智能化?

时间:2014-02-04 19:01:17

标签: angularjs-directive spinner angular-http-interceptors

我正在使用http拦截器指令来加载微调器,这是我的脚本代码:

createProfileModule.config(['$httpProvider', function ($httpProvider) {
    var $http,
        interceptor = ['$q', '$injector', function ($q, $injector) {
            var error;

            function success(response) {
                // get $http via $injector because of circular dependency problem
                $http = $http || $injector.get('$http');
                if($http.pendingRequests.length < 1) {
                    $('#loadingWidget').hide();
                }
                return response;
            }

            function error(response) {
                // get $http via $injector because of circular dependency problem
                $http = $http || $injector.get('$http');
                if($http.pendingRequests.length < 1) {
                    $('#loadingWidget').hide();
                }
                return $q.reject(response);
            }

            return function (promise) {

                $('#loadingWidget').show();
                return promise.then(success, error);
            }
        }];

    $httpProvider.responseInterceptors.push(interceptor);
}]);

在HTML中,我使用所需的CSS调用div这样的

<div id="loadingWidget" style="display:none;"></div>


 <style>
#loadingWidget { position: absolute; z-index:2;
    top: 0;
    left: 0;
    height:100%;
    width:100%;
    background: #000000 url(/ERegII-1.0/images/ajax-loader.gif) no-repeat center; 
    cursor: not-allowed;
    filter: alpha(opacity=60);
    opacity: 0.6;
     content:'Loading..';
     background-size:100px 100px;

     }
</style>

我想让这个微调器变得聪明。我不想在每个小的http调用上显示微调器。因此,如果我的请求非常小而且需要几毫秒,我不想显示微调器。我想给微调器加一​​个延迟时间..让我们说2秒钟。因此,如果请求超过2秒,这个微调器应该显示,否则我不想显示它。 有人可以帮我找到解决方案吗? 我试过https://github.com/ajoslin/angular-promise-tracker,但似乎对我不起作用。

有人可以帮助我让它更聪明吗?

1 个答案:

答案 0 :(得分:0)

如果请求的持续时间超过2秒,您可以使用$ timeout服务(或本机setTimeout)来延迟显示加载程序。以下是$ timeout ..

的示例
createProfileModule.config(['$httpProvider', '$timeout', function ($httpProvider, $timeout) {
...
var finished = true;

return function (promise) {
    finished = false;
    $timeout(function () {
        if (!finished) $('#loadingWidget').show();
    }, 2000); // wait 2 seconds
    return promise.then(success, error).finally(function () {
        finished = true;
    });
}

我正在使用一个名为'finished'的局部变量来跟踪请求是否已完成。我们在每个请求之前将它设置为false,并在promise的'finally'回调中将它设置为true以表示请求已完成。然后,您只需使用$ timeout延迟加载器的显示2秒,并仅在完成时显示它仍为假

相关问题