Below is my interceptor which handles global errors. But I want to bypass some http requests. Any suggestions ?
var interceptor = ['$rootScope', '$q',function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "./index.html#/404";
return;
}
if (status == 0) {
window.location = "./index.html#/nointernet";
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
So now to bypass the interceptor we can use HttpBackend. For more details about it, please refer to this. When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain. So as per the definition, we can surely use it for our current use case.
Later, you need to create one interceptor method with two arguments. The arguments would be the HTTP request and the HTTP handler. In the method's body, you can change the code at your convenience. After making the changes, just call the handle method of the HTTP handle using the HTTP request object.
AngularJS interceptors offer a convenient way to modify request made by the $http service both before they are sent and after they return.
I was able to implement this functionality simply by adding a property to the config object of the $http request. ie. ignore401
. Then, in my interceptor, in the response error handler, check for the property on the config object, and if it is present, do not forward to login or whatever else you do on a 401 response.
First, the interceptor:
$provide.factory('authorization', function() {
return {
...
responseError: (rejection) => {
if (rejection.status === 401 && !rejection.config.ignore401) {
// redirect to login
}
return $q.reject(rejection);
}
};
});
Then, for any request that I want to bypass the 401 error handler:
$http({
method: 'GET',
url: '/example/request/to/ignore/401error',
ignore401: true
});
Hope that helps.
I'm solving this as follows:
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
var hideUrl = "benefit/getall"; // don't show the loading indicator for this request
var hide = (config.url.indexOf(hideUrl)); // is this isn't -1, it means we should hide the request from the loading indicator
if(hide == -1)
{
$rootScope.$broadcast('loading:show')
}
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
});
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