</>
Skip to content
Angular lessons (33/43)

Angular — Interceptors

What are Interceptors?

Interceptors modify HTTP requests and responses.

Basic Interceptor

// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  
  if (token) {
    const cloned = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
    return next(cloned);
  }
  
  return next(req);
};

Register Interceptor

// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';

export const appConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ]
};

Loading Interceptor

export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const loadingService = inject(LoadingService);
  
  loadingService.show();
  
  return next(req).pipe(
    finalize(() => loadingService.hide())
  );
};

Error Interceptor

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        // Handle unauthorized
      } else if (error.status === 500) {
        // Handle server error
      }
      return throwError(() => error);
    })
  );
};

Mini Practice

  1. Create an auth interceptor
  2. Add loading indicator
  3. Handle errors globally
  4. Chain multiple interceptors

Up Next

Continue with Authentication — implementing auth.

Related Topics

Frequently Asked Questions about Interceptors

What is Interceptors in Angular?

Interceptors is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interceptors?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interceptors.

Why is Interceptors important in Angular?

Interceptors is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.