DEV Community

Cover image for What is Interceptor in Angular and how to use Interceptor in Angular
Omama Aslam
Omama Aslam

Posted on

What is Interceptor in Angular and how to use Interceptor in Angular

*In this artical we are going to learn : *

  1. What is an Angular HTTP Interceptor
  2. How to Create HTTP Interceptor
  3. 10 Ways to Use Interceptors in Angular

An application is incomplete without the backend server that displays data on UI. Various backend servers are available on the internet. Most application uses JSON and XML servers to perform their tasks. The API is used for the backend communication between components and methods. This communication is based on two significant concepts: authorization and authentication.

Interceptors are another significant part of Angular programming. They are used to modify the HTTP requests by adding several functionalities.

Authentication determines the security level of an application. The authentication check is placed on the user’s identity to make a good connection.

In contrast to this, authorization is a concept used to determine a user's authority.

Interceptor in angular is a great way to modify your code and make it more readable. Also, they are used in various other fields, which we will discuss later.

What is an Angular HTTP Interceptor

The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators. The interceptor is used to perform various functions and methods to perform specific tasks.

How to Create HTTP Interceptor

Before implementing an angular interceptor, you must create one. So, here we will help you create a service that will implement the HTTP interceptor angular interface. Here are the code snippets and examples to create an interceptor of your own.

  • First, create an injectable service.
@Injectable() export class AppHttpInterceptor implements HttpInterceptor {
Enter fullscreen mode Exit fullscreen mode
  • Now, implement the intercept method within the above class.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// do whatever you want to do with this request
return next.handle(req);
Enter fullscreen mode Exit fullscreen mode
  • Then add the class within the root module. Use the token named HTTP_INTERCEPTOR.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true
}
]
Enter fullscreen mode Exit fullscreen mode

10 Ways to Use Interceptors in Angular

There are various ways to use the angular HTTP interceptor. We have selected the top 10 most straightforward ways to use the angular HTTP interceptor. We will study them with relevant codes and examples.

  1. Loaders

Interceptors can be used as loaders whenever there exist different active requests. A loader function with both, hide and show features is used to handle the requests.

  1. URL

Changing the URLs is what the interceptor angular is capable of. You can change the URL, and the interceptor will behave like an API interceptor used to add prefixes.

  1. Headers

Angular interceptors manipulate the headers as they provide features such as authentication and authorization. The angular HTTP interceptors are used to protect the application against XSRF.

  1. Converting

Interceptor can even convert the format of an API that we receive. A more likely example is to convert the XML file to a JSON file.

  1. Errors

Interceptors are used in two ways to detect the errors- retry the HTTP call, and the second one is to keep a check on the status of the exception that occurred.

There are various HTTP error codes such as error codes 400, 500, and 200 and their series, which are to be handled individually. The error code 500 determines that the API has not received the request. The error code 401 means that the access token is no longer active.

  1. Notifications

Interceptors can even show various messages as notifications. In the below example, we have printed an “object created” message on the console. The notifications can also be displayed whenever we detect an error.

return next.handle(req).pipe(
tap((event: HttpEvent<any>) =>{ 
 if(event instanceof HttpResponse && event.status === 200) {
  this.toastr.success("Object Created");
}
})
)
Enter fullscreen mode Exit fullscreen mode
  1. Fake backend

As the name suggests, the fake backend is used to develop the application when the backend doesn’t exist. The response is based on the request, after which we return an observable object of the HTTP request. The code snippet is attached below-

const body = { 
 FirstName: "Omama",
 LastName: "Aslam"
};

return of(new HttpResponse({ status: 200, body: body}));
Enter fullscreen mode Exit fullscreen mode
  1. Profiling

Interceptors have the ability to both requests and respond simultaneously. They can even log the HTTP operation without any time delay. So, it becomes easy to note the time of both the request and the response and can be consoled together.

Different profiles can be logged into the database to get the information.

const started = Date.now();
let ok: string;

return next.handle(req).pipe(
tap(
(event: HttpEvent<any>) = ok = event instanceof HttpResponse ? 'successed' : '', 
(error: HttpErrorResponse) => ok: 'failed'
), 
finalize(()=>{
const elapsed = date.now() - started;
const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`
})
);
Enter fullscreen mode Exit fullscreen mode
  1. Authentication

Authentication is the basic functionality added to any application to check the user’s authentication. This is a common and basic use of the interceptors to make a check-in at the application’s usage. It connects various parameters such as the refresh tokens, adds bearer tokens, and redirects to the login URL.

  1. Catching

Interceptors are capable enough to detect any errors as it handles the requests besides forwarding them to the handle method. We will use a key-value map where the key will be more like a URL. The observable response can be returned directly to the handle function as soon as we find any relevant response on the map.

This is feasible as it saves a lot of time and energy. The developers do not always need to search everything in the backend when they have already caught one.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../weblib/services/auth.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService,
        private router: Router) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ((err.status === 401 || err.status === 403) && !request.url.includes('unauth')) {
                // auto logout if 401 response returned from api
                this.authService.logout(true);
                //this.router.navigate(['login']);
                location.reload(true);
            }
            // tslint:disable-next-line:max-line-length
            let error = 'Unable to process request at this time. If problem persists please notify your admin.';
            //if (err.error) { error = err.error.message || err.error.error; }
            if (err.error) { error = err.error.exceptionMessage || err.error || err.message; }
            return throwError(`Status: ${err.status} | ${error}`);
        }));
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
omamaaslam profile image
Omama Aslam

awesome post