Interceptors for HTTP Requests – Angular
Welcome to this comprehensive, student-friendly guide on Angular Interceptors! 🎉 If you’re new to Angular or just want to deepen your understanding of how to handle HTTP requests more effectively, you’re in the right place. Don’t worry if this seems complex at first—by the end of this tutorial, you’ll have a solid grasp of interceptors and how to use them in your Angular applications. Let’s dive in! 🚀
What You’ll Learn 📚
- What interceptors are and why they’re useful
- How to create and implement a basic interceptor
- Progressively complex examples to deepen your understanding
- Common questions and troubleshooting tips
Introduction to Interceptors
In Angular, interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses. Think of them as a middleman that can tweak your requests before they leave your app and responses before they reach your app. This can be super handy for adding headers, logging, error handling, and more! 🌟
Key Terminology
- Interceptor: A service that implements the
HttpInterceptor
interface to intercept and handle HTTP requests and responses. - HTTP Request: A communication method used to request data from a server.
- HTTP Response: The data sent back from the server in response to an HTTP request.
Simple Example: Creating a Basic Interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class SimpleInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
console.log('HTTP Request intercepted!');
return next.handle(req);
}
}
In this simple example, we create an interceptor that logs a message every time an HTTP request is made. Here’s what’s happening:
- We import necessary modules and interfaces.
- We create a class
SimpleInterceptor
that implementsHttpInterceptor
. - The
intercept
method logs a message and then callsnext.handle(req)
to pass the request to the next handler.
Progressively Complex Examples
Example 1: Adding an Authorization Header
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
setHeaders: {
Authorization: `Bearer YOUR_TOKEN_HERE`
}
});
return next.handle(clonedRequest);
}
}
In this example, we clone the request and add an Authorization header. This is useful for sending tokens with your requests for authentication purposes.
Example 2: Logging Requests and Responses
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
console.log('Request:', req);
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
console.log('Response:', event);
}
})
);
}
}
This interceptor logs both the request and the response. We use the tap
operator to perform side-effects like logging without altering the response.
Example 3: Handling Errors
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}
}
Here, we handle HTTP errors by catching them and logging the error details. We use catchError
to handle errors in the response stream.
Common Questions and Answers
- What is an interceptor in Angular?
An interceptor is a service that can intercept and manipulate HTTP requests and responses in Angular applications.
- How do I register an interceptor?
Register an interceptor in the
providers
array of your Angular module usingHTTP_INTERCEPTORS
. - Can interceptors modify HTTP requests?
Yes, interceptors can modify requests by cloning them and applying changes.
- How do interceptors handle errors?
Interceptors can use the
catchError
operator to handle errors in the response stream. - Why use interceptors?
Interceptors are useful for tasks like adding headers, logging, and error handling, which can be applied globally to all HTTP requests.
Troubleshooting Common Issues
Ensure your interceptor is registered correctly in the providers array, or it won’t be applied to HTTP requests.
If your interceptor isn’t working, check for typos in your imports and ensure you’re using the correct interfaces and operators.
Remember that interceptors are executed in the order they are provided, so the sequence can affect the behavior of your requests and responses.
Practice Exercises
- Create an interceptor that adds a custom header to all outgoing requests.
- Modify the logging interceptor to log only specific types of requests.
- Implement an interceptor that retries failed requests a certain number of times before failing.
For more information, check out the official Angular documentation on interceptors.