Understanding Angular Interceptors: A Friendly Guide

Paul Chesa
4 min readJul 7, 2024

--

Angular interceptors are a powerful feature that can help you manage HTTP requests and responses in your Angular applications. But what exactly are they, and how do they work? Let’s dive into the world of Angular interceptors.

What Are Angular Interceptors?

Imagine you’re a teacher in a big school. Every day, you handle lots of students and activities. Now, let’s say you have some helpers who assist you with specific tasks like checking if students have their homework, ensuring they wear their uniforms, or even reminding them to stay quiet in the library.

In Angular, these helpers are called interceptors. They are functions or classes that you can run for each HTTP request and response, allowing you to implement common patterns such as authentication, logging, and caching.

Types of Helpers (Interceptors)

  1. Functional Interceptors: These are like helpers who know exactly what to do and follow a specific routine every time. They are reliable and predictable, especially in a busy school with many activities.

2. DI-based Interceptors: These helpers are assigned tasks based on the situation and hierarchy. Sometimes, their tasks can overlap, making it tricky to predict who does what first.

How Do They Work?

When a student (HTTP request) enters the school (your application), it goes through several checkpoints (interceptors). Each helper (interceptor) at these checkpoints can:

  • Check if the student has a permission slip (authentication).
  • Record the student’s arrival time (logging).
  • Remind the student about their homework (modifying requests).
  • Keep track of any special instructions (request and response metadata).

Example of a Helper Task

Imagine you have a helper named “Logger” at the school entrance who notes down the names of students entering the school. In Angular, this would look like:

export function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
console.log(req.url); // The helper logs the student’s name
return next(req); // The student moves to the next checkpoint
}

Setting Up Helpers

You tell your school administration (Angular app) about your helpers (interceptors) so they know which checkpoints (interceptors) to use. You list them in the order you want them to act:

bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptors([loggingInterceptor, cachingInterceptor]),
)
]
});

Here, the “Logger” helper works first, followed by another helper, say, a “Cacher” who checks if the student has already submitted their homework recently.

Modifying Requests

Sometimes, a helper might need to change something about the student. For instance, if the student forgets their badge, the helper gives them a temporary one:

const reqWithHeader = req.clone({
headers: req.headers.set('X-New-Header', 'new header value'),
});

This ensures the student (request) has everything needed before moving forward.

Advanced Tasks

Helpers can also do more complex tasks. For instance, they can create new responses (like making a new entry in a logbook) or handle retries if something goes wrong.

Dependency Injection (DI)

Just like some helpers might need tools or information (like the list of students), interceptors can use services provided by Angular’s DI system to get what they need.

Context Tokens

Sometimes, you need to pass special instructions to the helpers. This is like giving a student a note to show to the helper at the next checkpoint. These notes (context tokens) tell the helper what special actions to take.

In Angular, interceptors are like dedicated helpers handling various tasks for each HTTP request passing through your app. They can log, modify, retry, and even create responses, ensuring that each request is processed smoothly and efficiently. Just like a well-organized school with helpful assistants, interceptors keep your Angular app running efficiently and securely.

By understanding and utilizing Angular interceptors, you can significantly enhance the functionality and reliability of your applications. So, go ahead and set up your interceptors, and let your app’s HTTP requests and responses be managed seamlessly by these helpful “school helpers”!

--

--

Paul Chesa
Paul Chesa

Written by Paul Chesa

Angular developer | Frontend Developer | Proficient in Typescript and JavaScript | Parva res est

No responses yet