In AngularJS, how to stop ongoing $http calls on query change

大城市里の小女人 提交于 2020-01-19 07:42:16

问题


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

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:


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.



来源:https://stackoverflow.com/questions/16962232/in-angularjs-how-to-stop-ongoing-http-calls-on-query-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!