【问题标题】:How to make the http interceptor spinner smart?如何使 http 拦截器微调器智能?
【发布时间】:2014-06-11 04:47:00
【问题描述】:

我正在使用 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,但似乎对我不起作用。

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

【问题讨论】:

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


    【解决方案1】:

    如果请求花费的时间超过 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 秒,并且仅在 finished 仍然为 false 时才显示它

    【讨论】:

    • 感谢查理的帮助!
    猜你喜欢
    • 2018-07-08
    • 2020-05-24
    • 1970-01-01
    • 2020-11-08
    • 2023-03-13
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多