2013-09-30 99 views
0

我有很多頁面,我使用$http來處理請求(獲取數據,更新),我必須每次使用ajax-loading.gif是否有可能知道,該請求正在處理中

現在,我需要做的是這樣的:

<div ng-show="model == null || ajaxUpdating"> 
    <div> 
     <img src="~/Content/Images/gif-load.gif" /> 
     <p>Waiting server respone...</p> 
    </div> 
</div> 

在這裏,我有ajaxUpdating標誌,我請求之前初始化和successerror回調設置爲false:

$scope.ajaxUpdating = true; 
    $http({ 
     url: updateUrl, 
     method: 'POST' 
    }). 
    success(function (data, status) { 
     window.location.href = settings.redirectAfterOk; 
    }). 
    error(function (data, status) { 
     $scope.ajaxUpdating = false; 
     alert(data.errorMsg || settings.errors.update); 
    }); 

所以,我想知道,是否有可能檢查,如果現在請求處理?我不想用這麼多標誌的每一個地方在我的代碼,它可能是更容易,如果我只是寫:

$http.isProcessing

例如。

Thx you。

+0

據因爲ajax是異步的,因此知道它何時完成的回調機制。所以你需要使用標誌或類似的東西。 – luiso1979

回答

3

如果需要加載GIF每當一個Ajax HTTP請求正在進行中,您可以在配置這樣的設置了一個攔截:

var myApp = angular.module('myApp', []).config(
    [ '$routeProvider', '$locationProvider', 
    function($routeProvider, $locationProvider) { 
    //routes here 
}]).config(function($httpProvider) { 
//show a loading div when a http request is running 
     var numLoadings = 0; 
     var loadingScreen = $('<div style="position:fixed;top:0;left:0;right:0;bottom:0;z-index:10000;background-color:gray;background-color:rgba(70,70,70,0.2);"><img style="position:absolute;top:50%;left:50%;" alt="" src="css/loading.gif" /></div>').appendTo($('body')).hide(); 
     $httpProvider.responseInterceptors.push(function() { 
      return function(promise) { 
       numLoadings++; 
       loadingScreen.show(); 
       var hide = function(r) { if (!(--numLoadings)) loadingScreen.hide(); return r; }; 
       return promise.then(hide, hide); 
      }; 
     }); 
    }); 

$http,尋找攔截

+1

順便說一句,最好是我們推這個HTML和只顯示隱藏它-_- – nXqd

+0

這真是太棒了! – FSou1

相關問題