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');
$http is an AngularJS service for reading data from remote servers.
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With