在 AngularJS 中,如何在查询更改时停止正在进行的 $http 调用 [英] In AngularJS, how to stop ongoing $http calls on query change
问题描述
我正在并行调用 4 到 10 个 $http get 调用.但是在用户搜索操作之后,我需要显示到相同的视图但结果不同.我填充数据集和新的 $http 查询调用.但是之前的 $http 调用(promises)仍在填充或在起作用,影响 $scope.
I'm calling 4 to 10 $http get calls in parallel. But after user search action I need display to same view but with different result. I populate set of data and new $http query calls. But the previous $http invocations(promises) are still populating or in action, effecting $scope.
我可能的肮脏解决方案是..
My possible dirty solution is ..
使用多应用(多模块)页面,该页面可以具有由动态应用控制的动态区域.在用户事件中删除与事件对应的元素.例如,搜索结果,如果我想使用不同的 $http 调用显示来自不同来源的结果.如果用户使用 new 关键字搜索,我将删除结果 ng-app 元素并引导新元素.
Using multi-app(multimodule) page which can have dynamic regions controlled by a dynamic app. On user events remove the element which correspond to the event. Example, search result, if I want to display results from different sources using different $http calls. If user searches with new keyword , I'm going to remove result ng-app element and bootstrap new element.
推荐答案
你应该使用 1.1.5 版本,它能够取消 $http 请求:
You should use version 1.1.5, which has the ability to cancel $http requests:
https://github.com/angular/angular.js/blob/master/CHANGELOG.md
// set up a dummy canceler
var canceler = $q.defer();
// use it as a timeout canceler for the request
$http({method: 'GET', url: '/some', timeout: canceler.promise}).success(
function (data) { alert("this won't be displayed on cancel"); }
).error(
function (data) { alert("this will be displayed on cancel"); }
)
// now, cancel it (before it may come back with data)
$rootScope.$apply(function() {
canceler.resolve();
});
您可以对所有请求使用相同的取消器,并在开始新集合之前解决它.
you can use the same canceler for all the requests, and resolve it just before starting the new set.
这篇关于在 AngularJS 中,如何在查询更改时停止正在进行的 $http 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!