angularjsHow can I use AngularJS interceptors to modify HTTP requests?
AngularJS interceptors are a great way to modify HTTP requests. They allow you to modify the request before it’s sent, and modify the response after it’s received. Here is an example of using an interceptor to modify an HTTP request:
// Create the interceptor
app.factory('myHttpInterceptor', function($q) {
return {
// optional method
'request': function(config) {
// do something on success
config.headers['X-My-Header'] = 'MyHeaderValue';
return config;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
// Register the interceptor
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
In the example above, the interceptor is created and registered with the $httpProvider
. The request
method is called whenever an HTTP request is made, and the responseError
method is called whenever an error is encountered. In the request
method, the header X-My-Header
is added to the request with the value MyHeaderValue
.
In summary, AngularJS interceptors can be used to modify HTTP requests. The example above shows how to add a custom header to a request.
Code Parts Explanation
app.factory('myHttpInterceptor', function($q) {
- This line creates a new factory calledmyHttpInterceptor
.'request': function(config) {
- This line creates therequest
method which is called whenever an HTTP request is made.config.headers['X-My-Header'] = 'MyHeaderValue';
- This line adds a custom header calledX-My-Header
with the valueMyHeaderValue
to the request.'responseError': function(rejection) {
- This line creates theresponseError
method which is called whenever an error is encountered.$httpProvider.interceptors.push('myHttpInterceptor');
- This line registers the interceptor with the$httpProvider
.
Relevant Links
More of Angularjs
- How can I create an editable AngularJS application?
- How can I use Angular to zoom in and out of a div?
- How do I use Angular to zip files?
- How do I use Angular Zone to detect and run Angular change detection?
- How do I copy an element in AngularJS?
- How can I use AngularJS to create a zone in my software development project?
- How can I use query parameters in an AngularJS application?
- How do I use Angular with YAML?
- How can I use Zone.js with Angular to detect and act upon asynchronous events?
- How can I use the YouTube API with Angular?
See more codes...