Using Interceptor in Angular

Using Interceptor in Angular

In this tutorial, we are going to discuss how to use HTTP interceptors in Angular. Interceptors provide a way to modify HTTP requests or responses globally, allowing developers to manage authentication tokens, error handling, logging, and more.

What is an HTTP Interceptor?

An HTTP interceptor is a special type of service in Angular that intercepts HTTP requests and responses before they reach their destination. This is useful for:

  • Adding authentication headers (e.g., JWT tokens)
  • Logging HTTP requests and responses
  • Error handling and retry mechanisms

Setting Up an HTTP Interceptor

To create an interceptor, use the Angular CLI:

ng generate service auth-interceptor

Now, modify the generated auth-interceptor.service.ts file:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = this.authService.getToken();
    const modifiedReq = req.clone({
      setHeaders: { Authorization: `Bearer ${authToken}` }
    });
    return next.handle(modifiedReq);
  }
}

Registering the Interceptor

To enable the interceptor, add it to the app.module.ts file:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth-interceptor.service';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
export class AppModule {}

Handling Errors with Interceptors

Interceptors can also be used to handle API errors globally. Modify the interceptor to catch errors:

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).pipe(
    catchError(error => {
      console.error('Error occurred:', error);
      return throwError(error);
    })
  );
}

Benefits of Using Interceptors

  • Centralized authentication handling: Automatically attach authentication tokens to every request.
  • Error handling: Catch and process errors globally.
  • Logging and debugging: Monitor HTTP requests and responses easily.
  • Request modification: Add custom headers, transform requests, and more.

Conclusion

Using HTTP interceptors in Angular provides a powerful mechanism for managing HTTP requests efficiently. By implementing interceptors, you can streamline authentication, improve error handling, and maintain cleaner code.

I hope you found this tutorial helpful. Happy coding!

Thanks!

Post a Comment

0 Comments