Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 285
Raghu Avatar asked Jun 06 '13 12:06

Raghu


1 Answers

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.

like image 89
rewritten Avatar answered Nov 16 '22 01:11

rewritten