AngularJ는 루트 변경 시 보류 중인 $http 요구를 모두 중단합니다.
먼저 코드를 검토하십시오.
app.module
var app = angular.module('Nimbus', ['ngRoute']);
route.displaces를 설정합니다.
app.config(function($routeProvider) {
    $routeProvider
    .when('/login', {
        controller: 'LoginController',
        templateUrl: 'templates/pages/login.html',
        title: 'Login'
    })
    .when('/home', {
        controller: 'HomeController',
        templateUrl: 'templates/pages/home.html',
        title: 'Dashboard'
    })
    .when('/stats', {
        controller: 'StatsController',
        templateUrl: 'templates/pages/stats.html',
        title: 'Stats'
    })
}).run( function($q, $rootScope, $location, $route, Auth) {
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
        console.log("Started");
        /* this line not working */
        var canceler = $q.defer();
        canceler.resolve();
    });
    $rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
        $rootScope.title = ($route.current.title) ? $route.current.title : 'Welcome';
    });
 })
home-controller.syslog
app.controller('HomeController',
    function HomeController($scope, API) {
        API.all(function(response){
            console.log(response);
        })
    }
)
stats-controller.syslog
app.controller('StatsController',
    function StatsController($scope, API) {
        API.all(function(response){
            console.log(response);
        })
    }
)
api.module
app.factory('API', ['$q','$http', function($q, $http) {    
    return {
        all: function(callback) {
            var canceler = $q.defer();
            var apiurl = 'some_url'
            $http.get(apiurl,{timeout: canceler.promise}).success(callback);
        }
    }
}]);
홈에서 stats로 이동하면 API가 http 요청을 전송합니다.이렇게 http 콜이 많으니까 코드 몇 줄만 붙여놨어요.
내가 필요한 건
  취소하다  routechangestart 또는 성공 시 보류 중인 모든 http 요청을 중단합니다.
또는 같은 것을 실장할 수 있는 다른 방법이 있습니까?
이걸 위한 개념적인 코드를 짜놨어요.필요에 맞게 조정해야 할 수도 있습니다.이 있습니다.pendingRequests요청을 추가, 가져오기 및 취소하기 위한 API를 가진 서비스,httpService그것은 포장되어 있다$http모든 요구가 추적되는 것을 확인합니다.
를 활용하여$httpconfig object(클릭) 보류 중인 요청을 취소하는 방법을 얻을 수 있습니다.
plnkr을 작성했습니다만, 검색한 테스트 사이트는 통상 0.5초 이내에 응답하기 때문에 취소되는 요청을 확인하려면 빠른 손가락이 필요합니다.단, devtools 네트워크 탭에서 요청이 취소되는 것을 확인할 수 있습니다.당신의 경우, 당신은 분명히 그 살인 사건을cancelAll()적절한 사건을 요구하다$routeProvider.
컨트롤러는 개념을 보여주기 위해 존재합니다.
angular.module('app', [])
// This service keeps track of pending requests
.service('pendingRequests', function() {
  var pending = [];
  this.get = function() {
    return pending;
  };
  this.add = function(request) {
    pending.push(request);
  };
  this.remove = function(request) {
    pending = _.filter(pending, function(p) {
      return p.url !== request;
    });
  };
  this.cancelAll = function() {
    angular.forEach(pending, function(p) {
      p.canceller.resolve();
    });
    pending.length = 0;
  };
})
// This service wraps $http to make sure pending requests are tracked 
.service('httpService', ['$http', '$q', 'pendingRequests', function($http, $q, pendingRequests) {
  this.get = function(url) {
    var canceller = $q.defer();
    pendingRequests.add({
      url: url,
      canceller: canceller
    });
    //Request gets cancelled if the timeout-promise is resolved
    var requestPromise = $http.get(url, { timeout: canceller.promise });
    //Once a request has failed or succeeded, remove it from the pending list
    requestPromise.finally(function() {
      pendingRequests.remove(url);
    });
    return requestPromise;
  }
}])
// The controller just helps generate requests and keep a visual track of pending ones
.controller('AppCtrl', ['$scope', 'httpService', 'pendingRequests', function($scope, httpService, pendingRequests) {
  $scope.requests = [];
  $scope.$watch(function() {
    return pendingRequests.get();
  }, function(pending) {
    $scope.requests = pending;
  })
  var counter = 1;
  $scope.addRequests = function() {
    for (var i = 0, l = 9; i < l; i++) {
      httpService.get('https://public.opencpu.org/ocpu/library/?foo=' + counter++);  
    }
  };
  $scope.cancelAll = function() {
    pendingRequests.cancelAll();
  }
}]);
사용할 수 있습니다.$http.pendingRequests그렇게 할 수 있어요.
먼저 요청을 할 때 다음을 수행합니다.
var cancel = $q.defer();
var request = {
    method: method,
    url: requestUrl,
    data: data,
    timeout: cancel.promise, // cancel promise, standard thing in $http request
    cancel: cancel // this is where we do our magic
};
$http(request).then(.....);
여기서 보류 중인 요청은 모두 취소됩니다.$routeChangeStart 
$rootScope.$on('$routeChangeStart', function (event, next, current) {
    $http.pendingRequests.forEach(function(request) {
        if (request.cancel) {
            request.cancel.resolve();
        }
    });
});
이렇게 하면 요청에 '취소' 필드를 제공하지 않음으로써 특정 요청이 취소되지 않도록 '보호'할 수도 있습니다.
저는 이것이 요청을 중단하기 위한 최선의 해결책이라고 생각합니다.인터셉터와 $routeChangeSuccess 이벤트를 사용하고 있습니다.http://blog.xebia.com/cancelling-http-requests-for-fun-and-profit/
Angular는 처음이라 최적은 아닐 수 있습니다.또 다른 해결책으로는 $http 요청 시 "timeout" 인수를 추가하는 방법이 있습니다.
내가 모든 휴게소를 호출하는 공장에서, 이 논리를 생각해 봐.
module.factory('myactory', ['$http', '$q', function ($http, $q) {
    var canceler = $q.defer();
    var urlBase = '/api/blabla';
    var factory = {};
    factory.CANCEL_REQUESTS = function () {
        canceler.resolve();
        this.ENABLE_REQUESTS();
    };
    factory.ENABLE_REQUESTS = function () {
        canceler = $q.defer();
    };
    factory.myMethod = function () {
        return $http.get(urlBase, {timeout: canceler.promise});
    };
    factory.myOtherMethod= function () {
        return $http.post(urlBase, {a:a, b:b}, {timeout: canceler.promise});
    };
    return factory;
}]);
각진 앱 구성에는 다음과 같은 기능이 있습니다.
return angular.module('app', ['ngRoute', 'ngSanitize', 'app.controllers', 'app.factories',
    'app.filters', 'app.directives', 'ui.bootstrap', 'ngGeolocation', 'ui.select' ])
.run(['$location', '$rootScope', 'myFactory', function($location, $rootScope, myFactory) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        myFactory.CANCEL_REQUESTS();
        $rootScope.title = current.$$route.title;
    });
}]);
이렇게 하면 모든 "루트" 변경을 포착하고 해당 "타이머"로 설정된 모든 요청을 중지하여 중요한 항목을 선택할 수 있습니다.
누군가에게 도움이 됐으면 좋겠어요.안부 전해요
언급URL : https://stackoverflow.com/questions/23244389/angularjs-abort-all-pending-http-requests-on-route-change
'programing' 카테고리의 다른 글
| &을 포함하는 문자열을 삽입하는 방법 (0) | 2023.03.17 | 
|---|---|
| 봄 부츠에 백합 사투리 어떻게 넣어요? (0) | 2023.03.17 | 
| 각도 있는 프로젝트 아키텍처 (0) | 2023.03.12 | 
| 배열을 정렬하는 TypeScript (0) | 2023.03.12 | 
| WooCommerce 4+에서 제품에 커스텀 재고 상태를 추가하는 방법 (0) | 2023.03.12 |