bestsource

Angular js - 모든 $http()가 완료되었음을 감지합니다.

bestsource 2023. 3. 5. 10:12
반응형

Angular js - 모든 $http()가 완료되었음을 감지합니다.

그래, 나는 많은 것을 가지고 있어$http()모든 앱 코드에 전화가 걸려옵니다.

궁금한 게 있는데, 어떤 방법이 있을까요? / 베스트 프랙티스가$http()앱이 종료된 경우(성공/오류는 반환되는 내용에 관계없이 종료되었는지 확인만 하면 됨)

로딩될 때까지 로딩 gif를 보여줄 수 있도록?

감사해요.

다음과 같이 합니다.

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

다음으로 바인드된 이벤트를 사용합니다.$rootScopeanywhere(지시적으로 사용할 수 없음):

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

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

다음 날짜까지 모든 요청을 수행할 수 있습니다.$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]
});

사용.ng-if로드를 표시하거나 숨길 수 있습니다.gif.

만약 당신이 다른 것을 사용할 경우$http콜을 하고 나서count또는array에서$rootScope갱신할 때마다$http완성하다.을 기반으로 합니다.count또는array.length로드를 유효하게 하다gif.

@karaxuna의 답변을 사용하여 다음과 같은 솔루션을 구현합니다.플런커

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

언급URL : https://stackoverflow.com/questions/23361883/angular-js-detect-when-all-http-have-finished

반응형