Interceptors

The framework also provides an HTTP intercepting mechanism. It allows us to create common behaviors for different kinds of situations such as verifying whether a user is already authenticated or to gather information for auditing purposes.

request Interceptor
The first is the request interceptor. This interceptor is called before the request is being sent to the backend. It is very useful when we need to add information such as additional parameters or even headers to the request.

httpTimestamp Interceptor
In the following code, we create an interceptor called httpTimestampInterceptor, which adds the current time in milliseconds to each request that is made by the application:
parking.factory('httpTimestampInterceptor', function() {
return {
'request': function(config) {
var timestamp = Date.now();
config.url = config.url + "?x=" + timestamp;
return config;
}
}
});
requestError Interceptor
Something might happen with the request, causing an error. With the requestError interceptor, we can handle this situation. It is called when the request is rejected and can't be sent to the backend.

response Interceptor
The response interceptor is called right after the response arrives from the backend and receives a response as a parameter. It's a good opportunity to apply any pre-processing behavior that may be required.

responseError Interceptor
One of the most common intercepting situations is when the backend produces any kind of error, returning a status code to indicate unauthorized access, a bad request, a not found error, or even an internal server error. It could be handled by the responseError interceptor, which allows us to properly apply the correct behavior in each situation.

httpUnauthorized Interceptor
This httpUnauthorizedInterceptor parameter, in the following code, is responsible for handling the unauthorized error and changing the login property of $rootScope, indicating that the application should open the login dialog:
parking.factory('httpUnauthorizedInterceptor', function($q,
$rootScope) {
return {
'responseError': function(rejection) {
if (rejection.status === 401) {
$rootScope.login = true;
}
return $q.reject(rejection);
}
}
});
After defining the interceptors, we need to add them to $httpProvider using the config function of the Module API, as follows:
config.js
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpTimestampInterceptor');
$httpProvider.interceptors.push('httpUnauthorizedInterceptor');
});
Related Tutorial
2. ajax
5. Caching
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 # # # # #