Interceptors in AngularJS for handling requests globally

Loading

Interceptors in AngularJS allow developers to globally handle HTTP requests and responses. They are useful for:

Modifying request headers
Logging API calls
Handling authentication tokens
Centralized error handling
Request/response transformation

Interceptors work with the $httpProvider service and can be registered in an AngularJS module.


1. Creating an HTTP Interceptor

Interceptors are defined as factories that return an object with functions to intercept HTTP requests and responses.

Basic Interceptor Structure

app.factory("MyInterceptor", function($q) {
return {
request: function(config) {
console.log("Outgoing request: ", config);
return config;
},
response: function(response) {
console.log("Incoming response: ", response);
return response;
},
responseError: function(rejection) {
console.error("Request failed: ", rejection);
return $q.reject(rejection);
}
};
});

🔹 request(config): Modifies or logs outgoing requests.
🔹 response(response): Modifies or logs incoming responses.
🔹 responseError(rejection): Handles errors globally.


2. Registering an Interceptor

Once the interceptor is created, register it with $httpProvider.

app.config(function($httpProvider) {
$httpProvider.interceptors.push("MyInterceptor");
});

🔹 This ensures all API calls pass through the interceptor.


3. Adding Authentication Token in Requests

Interceptors help in attaching authentication tokens to every request.

app.factory("AuthInterceptor", function($q, AuthService) {
return {
request: function(config) {
var token = AuthService.getToken();
if (token) {
config.headers.Authorization = "Bearer " + token;
}
return config;
}
};
});

app.config(function($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
});

🔹 AuthService.getToken() retrieves the JWT token stored in local storage.
🔹 Adds Authorization: Bearer <token> in request headers.


4. Handling Global Errors

Interceptors help in catching API errors globally.

app.factory("ErrorInterceptor", function($q, $rootScope) {
return {
responseError: function(rejection) {
if (rejection.status === 401) {
$rootScope.$broadcast("unauthorized");
} else if (rejection.status === 500) {
alert("Server Error! Please try again.");
}
return $q.reject(rejection);
}
};
});

app.config(function($httpProvider) {
$httpProvider.interceptors.push("ErrorInterceptor");
});

🔹 Handles unauthorized errors (401) by broadcasting an event.
🔹 Alerts users when a 500 error occurs.


5. Logging All API Calls

Interceptors can be used for request logging.

app.factory("LoggerInterceptor", function($q) {
return {
request: function(config) {
console.log("Request made to: " + config.url);
return config;
},
response: function(response) {
console.log("Response received from: " + response.config.url);
return response;
}
};
});

app.config(function($httpProvider) {
$httpProvider.interceptors.push("LoggerInterceptor");
});

🔹 Logs all API requests and responses for debugging.


6. Chaining Multiple Interceptors

Multiple interceptors can be stacked together.

app.config(function($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
$httpProvider.interceptors.push("ErrorInterceptor");
$httpProvider.interceptors.push("LoggerInterceptor");
});

🔹 Executes interceptors in order, handling authentication, errors, and logging.

Leave a Reply

Your email address will not be published. Required fields are marked *