Using Interceptors in AngularJs
Posted By : Pulkit Chadha | 27-Sep-2017
Introduction:
The $http service helps us to communicate with the backend server and send HTTP requests.
Syntax:
var Interceptor = function ($q)
{
return {
request: function (config)
{
return config;
},
requestError: function (rejection)
{
return $q.reject(rejection);
},
response: function (result)
{
return result;
},
responseError: function (response)
{
return $q.reject(response);
}
}
}
interceptorApp = angular.module('interceptorApp', []).config(function ($httpProvider)
{
$httpProvider.interceptors.push(testInterceptor);
});
An interceptor is a factory() service and we need to register our factory with the $httpProvider.There is 4 interceptor:
1)Request.
2)RequestError.
3)Response.
4)ResponseError.
1) Request:
Before sending the request to the server., request interceptor is called.This takes only one argument i.e config obj and returns a config\ object.We can use request interceptor to add the authentication token to each HTTP request.
request: function (config) {
var token = AuthenticationService.get("auth");
config.headers['x-Auth-token'] = token;
return config;
}
2)RequestError:
This interceptor is called when
requestError: function (rejection) {
return $q.reject(rejection);
}
3)Response:
This interceptor is called after getting the response from the backend.We can use Response interceptor to add some extra keys in the response object.
response: function (obj) {
console.log('obj');
obj.timestamp=Date.now();
return obj;
},
4)ResponseError:
This interceptor is called if an $http request fails.We can use ResponseError interceptor for global error handling or redirect a user to the login page if we get status code 401.
responseError: function (response) {
if (response.status === 401) {
$location.path('/signin');
$flashService.showError = "Error occured";
}
if (response.status === 500) {
$flashService.showError = "Error occured";
$location.path('/Error')
}
return $q.reject(response);
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pulkit Chadha
Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.