An Introduction to Angular HTTP Interceptors
Implementing Interceptors

Writing an HTTP interceptor is dead simple, all you have to do is follow the following steps:

Create a class that implements HttpInterceptor , then decorate it with @Injectable Provide the interceptor

If you’re an Angular developer you already know how to provide services, there’s a catch though, for HttpInterceptor , you must provide it in the AppModule .

You’ll also do it like this:

It’s good practice to follow the instructions from the official documentation and create a new array in which to store all of the interceptors so that you only have to add new interceptors to the array and then provide the array in the AppModule ’s root.

The way interceptors work is that they first look at the request, then they call next on it. The following interceptor is a no operation interceptor, it does nothing:

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

Observable<HttpEvent<any>> {

return next.handle(req);

}

As far as I know, you can’t configure interceptors to activate on certain conditions (if you do, please let me know how!). You can configure an interceptor to activate only for some routes by inspecting the req parameter, as seen in this example :

If you have an application that uses JWT as an authentication method, you can write an HTTP interceptor that sets the JWT header if available. With the intercept method, you would do something like the following:

Thanks for reading! I hope you found this helpful.

The full code can be found here: https://stackblitz.com/angular/kmeqdgdrenj
['Denis Nuțiu']
['Angular', 'Framework', 'Front End Development', 'JavaScript', 'Https']