0
0
Angularframework~30 mins

Interceptors for request modification in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Interceptors for request modification
📖 Scenario: You are building an Angular app that talks to a server. Sometimes you need to add extra information to every request, like a secret token.Interceptors help you change requests before they go out.
🎯 Goal: Create an Angular HTTP interceptor that adds a custom header X-Custom-Token with value abc123 to every outgoing HTTP request.
📋 What You'll Learn
Create an Angular interceptor class named AuthInterceptor
Add the header X-Custom-Token with value abc123 to all HTTP requests
Register the interceptor in the providers array using HTTP_INTERCEPTORS
Use the intercept method with parameters req and next
💡 Why This Matters
🌍 Real World
Interceptors are used in real Angular apps to add tokens, handle errors, or log requests automatically.
💼 Career
Understanding interceptors is important for Angular developers working on secure and maintainable web applications.
Progress0 / 4 steps
1
Create the interceptor class
Create an Angular class called AuthInterceptor that implements HttpInterceptor. Import HttpInterceptor from @angular/common/http. Add the method intercept(req, next) that returns next.handle(req).
Angular
Need a hint?

Remember to import HttpInterceptor and create the intercept method that returns next.handle(req).

2
Add the custom header
Inside the intercept method, clone the req object and add a header X-Custom-Token with value abc123. Use req.clone({ setHeaders: { 'X-Custom-Token': 'abc123' } }) and assign it to a variable modifiedReq. Then pass modifiedReq to next.handle().
Angular
Need a hint?

Use req.clone to add headers without changing the original request.

3
Register the interceptor provider
In your Angular module or component providers array, add a provider object with provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, and multi: true. Import HTTP_INTERCEPTORS from @angular/common/http.
Angular
Need a hint?

Use multi: true to allow multiple interceptors.

4
Add the provider to the module
Add the interceptorProvider to the providers array of your Angular module or component decorator. For example, in @NgModule({ providers: [interceptorProvider] }).
Angular
Need a hint?

Put interceptorProvider inside the providers array in your module.