Top 7 ways to use Interceptors in Angular

 

Top 7 ways to use Interceptors in Angular



It Intercepts and handles an HttpRequest or HttpResponse.

Most interceptors convert the outgoing request before passing it on to the next interceptor in the chain. Handle (transformed rake). An interceptor can also alter the response event stream by applying additional RxJS operators to the stream returned by the next.take care ().

An interceptor may rarely fully handle the request and create a new event stream instead of invoking nextHandle(). This is acceptable behavior, but be aware that further interceptors will be skipped altogether.


interface HttpInterceptor {  

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>  

}  


It is rare but valid for an interceptor to return multiple responses on the event stream for a single request.




1. Authentication


And first on the list is authentication! It is just so fundamental for many applications that we have a proper authentication system in place. This is one of the most common use cases for interceptors and for a good reason. It fits right in!

There are several things connected to authentication we can do:

  1. Add bearer token
  2. Refresh Token
  3. Redirect to the login page


2. Caching


Since interceptors can handle requests by themselves, without forwarding them to next.handle(), we can use it for caching requests.

What we do is use the URL a the key in our cache that is just a key-value map. And if we find a response in the map, we can return an observable of that response, by-passing the next handler.

This increases performance since you don’t have to go all the way to the backend when you already have the response cached.


3. Fake backend


A mock or fake backend can be used in development when you do not have a backend yet. You can also use it for code hosted in StackBlitz.

We mock the response depending on the request. And then return an observable of HttpResponse.

const body = { 

  firstName: "Mock", 

  lastName: "Faker" 

};

return of(new HttpResponse(

  { status: 200, body: body }

));


4. Profiling


Because interceptors can process the request and response together, they can do things like time and log an entire HTTP operation. So we can capture the time of the request and the response and log the outcome with the elapsed time.


5. Errors

There are two use cases for errors that we can implement in the interceptor.

First, we can retry the HTTP call. 

Secondly, we can check the status of the exception. And depending on the status, we can decide what we should do.

return next.handle(req).pipe(

  retry(2),

  catchError((error: HttpErrorResponse) => {

    if (error.status !== 401) {

      // 401 handled in auth.interceptor

      this.toastr.error(error.message);      

    }

    return throwError(error);

  })

);


6. Notifications


Here we have many different cases where we could show messages. In my example, I show “Object created” every time we get a 201 created status back from the server.

return next.handle(req).pipe(
  tap((event: HttpEvent<any>) => {
    if (event instanceof HttpResponse && event.status === 201) {
      this.toastr.success("Object created.");
    }
  })
);

7. Headers


We can do a lot by manipulating headers. Some things are:

  • Authentication/authorization
  • Caching behavior; for example, If-Modified-Since
  • XSRF protection

We can easily add headers to the request in the interceptor.


const modified = req.clone({ 

  setHeaders: { "X-Man": "Wolverine" } 

});

return next.handle(modified);


Comments

Popular posts from this blog

Angular Best Practices and Coding Standards: A Guide for Developers

Route Web Server Request to App server through proxy