Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : How to prevent a request

Is it possible to prevent a request using angularjs interceptors ?

$provide.factory('myHttpInterceptor', function($q, someService) {
  return {
    'request': function(config) {
      // here I'd like to cancel a request depending of some conditions
    }
  }
});

$httpProvider.interceptors.push('myHttpInterceptor');
like image 327
Florian F Avatar asked Oct 31 '13 16:10

Florian F


People also ask

What is $HTTP in AngularJS?

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

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

Is HTTP request is synchronous or asynchronous in AngularJS?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.

What is HTTP request in angular?

HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.


1 Answers

In 1.1.5 and later you can use the 'timeout' property of the configuration object.

From the documentation:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

Simple example:

$provide.factory('myHttpInterceptor', function($q, someService) {
  return {
    'request': function(config) {

        var canceler = $q.defer();

        config.timeout = canceler.promise;

        if (true) {

            // Canceling request
            canceler.resolve();
        }

        return config;
    }
  }
});

$httpProvider.interceptors.push('myHttpInterceptor');
like image 92
tasseKATT Avatar answered Nov 03 '22 07:11

tasseKATT