Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel an $http request in AngularJS?

Given a Ajax request in AngularJS

$http.get("/backend/").success(callback); 

what is the most effective way to cancel that request if another request is launched (same backend, different parameters for instance).

like image 543
mpm Avatar asked Dec 18 '12 07:12

mpm


People also ask

How do I cancel http request?

We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won't be sent if the cancellation signal is sent before the HTTP request is done.

How do you cancel unsubscribe all pending HTTP requests angular 4+?

You can create an interceptor to apply takeUntil operator to every request. Then on route change you will emit event that will cancel all pending requests. Helper service. Hook on route changes somewhere in your app (e.g. onInit in appComponent).

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

What is event handling in AngularJS?

AngularJS includes certain directives which can be used to provide custom behavior on various DOM events, such as click, dblclick, mouseenter etc.


1 Answers

This feature was added to the 1.1.5 release via a timeout parameter:

var canceler = $q.defer(); $http.get('/someUrl', {timeout: canceler.promise}).success(successCallback); // later... canceler.resolve();  // Aborts the $http request if it isn't finished. 
like image 67
lambinator Avatar answered Sep 22 '22 15:09

lambinator