2

I am using http interceptor directive to load the spinner and here is my script code:

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);
}]);

and in HTML i am calling the div like this with the required CSS

<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>

What I want to make this spinner smart. I don't want to display the spinner on every small http call. So if my request if really small and it takes some milliseconds, I don't want to display the spinner. I want to add a delay time to the spinner.. let say 2 second. So if the request it taking more than 2 second this spinner should show up otherwise I don't want to display it. Can someone help me to find the solution for this? I have tried https://github.com/ajoslin/angular-promise-tracker but seems like doesn't work for me.

Can someone help me to make it smarter please?

4

1 回答 1

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 秒,并且仅在 finished 仍然为 false 时才显示它

于 2014-06-10T20:47:00.023 回答