Introduction

Interceptors intercept and mutate requests before sending them off to either another interceptor or the backend of an application using the HTTP client. They can be used to pass tokens in the header, pass a custom header, and deal with responses among other things they can do. In this tutorial, I will show you how to create a simple interceptor and how to use it.

Create an interceptor

In order to create an interceptor, we will use the Angular CLI and type the following:

ng g interceptor nameOfInterceptor

Once the interceptor has been created, it needs to be imported into a module. You can either import it into the AppModule (root module) or one of the feature modules. For this post, we will import it into the AppModule:

“Import interceptor into AppModule”

Examples

Output URL to browser console

We create an interceptor called OutputRequests. Angular CLI creates an interceptor with boilerplate code as follows:

“Boilerplate interceptor code”

For our example, all we will do is output to the browser console the URL that is being requested like so:

“Output to browser console “

Create custom header

We can also create a custom header that will be passed every time an AJAX call is made like so:

“Custom header in interceptor “

Conclusion

The above are some of the ways of how interceptors can be used in Angular.