2014-04-29 34 views
22

Ok i

merak ediyorum

algılamak için herhangi bir yolu/en iyi uygulama yoktur, $http() ton her uygulama koduna etrafında aramaları olduğunda çevresindeki tüm $http() uygulama bitti (başarı/hata ne döndükleri önemli değil, sadece bitmiş olup olmadığını bilmeniz gerekir)?

Yüklenene kadar yükleme gif gösterebilir miyim?

sayesinde

+3

İnsanlar zaten benzer bir şey oluşturdular. Http://codingsmackdown.tv/blog/2013/01/02/using-response-interceptors-to-show-and-hide-a-loading-widget/, http://codingsmackdown.tv/blog/2013/ adresine bakın. 04/20/kullanarak-yanıt-interceptors-to-show-ve-hide-a-yükleme-widget-redux/ – Chandermani

cevap

48

şöyle yapın:

angular.module('app').factory('httpInterceptor', ['$q', '$rootScope', 
    function ($q, $rootScope) { 
     var loadingCount = 0; 

     return { 
      request: function (config) { 
       if(++loadingCount === 1) $rootScope.$broadcast('loading:progress'); 
       return config || $q.when(config); 
      }, 

      response: function (response) { 
       if(--loadingCount === 0) $rootScope.$broadcast('loading:finish'); 
       return response || $q.when(response); 
      }, 

      responseError: function (response) { 
       if(--loadingCount === 0) $rootScope.$broadcast('loading:finish'); 
       return $q.reject(response); 
      } 
     }; 
    } 
]).config(['$httpProvider', function ($httpProvider) { 
    $httpProvider.interceptors.push('httpInterceptor'); 
}]); 

Ardından olay bağlı kullanmak $rootScope yerde (yönergede kullanmak tercih edilir): @karaxuna tarafından cevap kullanma

$rootScope.$on('loading:progress', function(){ 
    // show loading gif 
}); 

$rootScope.$on('loading:finish', function(){ 
    // hide loading gif 
}); 
+0

büyük bir çözümün gerçekten de direktifleri tespit etmemize gerek olup olmadığını merak ediyorum. sağ? – sbaaaang

+0

Eğer http() blok düzeni ve düzeni engellemek için blokları ayırmak ama bu benim kendi problemim – sbaaaang

+1

@sbaaaang Eğer '$ http' ile açısal yoldan yapılan tüm ajax istekleri yakalayacak. Elbette '$ .ajax' (veya herhangi bir xmlhttprequest) kullanırsanız – karaxuna

10

Eğer ng-if kullanma $q.all

$scope.request1 = $http.get('request1URL', {cache: false}); 
$scope.request2 = $http.get('request2URL', {'cache': false}); 
$scope.loading = true; 

$q.all([$scope.request1, $scope.request2]).then(function(values) { 
    $scope.loading = false; 
    // Do whatever you want 
    // values[0], values[1] 
}); 

bütün istekleri yürütmek eğer mümkündür, göstermek ve gif yükleme gizleyebilirsiniz.

durumda, farklı $http çağrı kullanırsanız, $rootScope bir count veya array ve her ne zaman $http tam güncelleyin. count veya array.length dayanarak, gif yükleniyor.

+0

Ben gerçekten ihtiyacım olan çözümler için sabırsızlanıyoruz aslında – sbaaaang

+0

Bu kesinlikle doğru bir çözümdür. –

+0

küresel olarak bunu yapmak istiyorsanız ve her bir denetleyicide/serviste $ q.all mantığını uygulamak zorunda kalmazsanız, – meffect

0

, aşağıda gibi benim Çözümü uygulamak . Plunker

<!doctype html> 
<html ng-app="ui.bootstrap.demo"> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script> 
    <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script> 
    <script> 
    var app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']); 

    app.config(['$httpProvider', function ($httpProvider) { 
     $httpProvider.interceptors.push(function ($q, $rootScope, $templateCache) { 
      var AjaxLoadingCount = 0; 
      return { 
       request: function (config) { 
        console.log("[config.interceptorService] request config", config);     
        if (++AjaxLoadingCount === 1) 
        { 
         if (!$templateCache.get(config.url)) { 
          $rootScope.$broadcast('AjaxLoading:Progress'); 
         } 
        } 
        return config || $q.when(config); 
       }, 
       requestError: function (rejection) { 
        console.log("[config.interceptorService] requestError rejection", rejection); 
        if(--AjaxLoadingCount === 0) $rootScope.$broadcast('AjaxLoading:Finish'); 
        return $q.reject(rejection); 
       }, 
       response: function (response) { 
        console.log("[config.interceptorService] response response", response); 
        if(--AjaxLoadingCount === 0) $rootScope.$broadcast('AjaxLoading:Finish'); 
        return response || $q.when(response);     
       }, 
       responseError: function (rejection) { 
        console.log("[config.interceptorService] responseError rejection", rejection); 
        if(--AjaxLoadingCount === 0) $rootScope.$broadcast('AjaxLoading:Finish'); 
        return $q.reject(rejection); 
       } 
      }; 
     }); 
    }]); 

    app.factory('ajaxFactory', function ($http) { 

     var ajaxFactory = {}; 
     ajaxFactory.LoadData = function() {    
      return $http({ 
       method: "GET", 
       url: "http://www.w3schools.com/angular/customers.php", 
      }); 
     }; 
     return ajaxFactory; 

    }); 

    app.controller('ModalDemoCtrl', function ($scope, ajaxFactory) { 
     $scope.doAjax = function() { 

      ajaxFactory.LoadData() 
      .success(function (data, status, headers, config) { 
       console.log("Data vai factory\n", JSON.stringify(data)); 
       console.log("Loading finish.");    
      }).error(function (data, status, headers, config) { 

      }); 
     }; 
    }); 

    app.directive("ajaxLoadingDirective", function ($uibModal) { 
     var modalInstance; 
     return { 
      restrict: 'EA', //E = element, A = attribute, C = class, M = comment    
      scope: true, 
      link: function (scope, elem, attrs) { 
       console.log("AjaxLoadingDirective.AjaxLoading:Progress"); 
       scope.$on("AjaxLoading:Progress", function() {     
        modalInstance = $uibModal.open({ 
         animation: true, 
         templateUrl: 'myModalContent.html' 
        }); 
       }); 
       return scope.$on("AjaxLoading:Finish", function() { 
        console.log("AjaxLoadingDirective.AjaxLoading:Finish"); 
        if(modalInstance === undefined) return; 
        modalInstance.dismiss(); 
       }); 
      } 
     } 
    }); 

    </script> 
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> 
    </head> 
    <body> 
    <div ng-controller="ModalDemoCtrl"> 
     <script type="text/ng-template" id="myModalContent.html"> 
      Loading data .......................    
     </script> 
     <button type="button" class="btn btn-default" ng-click="doAjax()">Execute Ajax</button> 
     <div ajax-loading-directive ></div> 
    </div> 
    </body> 
</html>