In this post we will be discussing briefly about Angular http interceptors. Before diving into http interceptors let’s first understand what is an interceptor in the context of Angular.

Image for post

Interceptor:

As the name interceptor suggests, interceptor in Angular is a mechanism to intercept an incoming or outgoing http request, modify the request/response globally before passing the request/response to the next handler. By interceptor we can edit a request before it hits an external api. The most common use of interceptors in Angular context is that they give us the ability to add additional headers like authentication tokens to the request so that the requests get authorized in the server side. Additionally we can handle errors coming due to http requests at one place. In this article we will see how we can leverage the power of interceptors to send JSON Web Tokens along with the request. But the utility of interceptors is not limited to sending authentication tokens only.

For learning interceptors, we need to have a Angular application set up which I won’t get into detail. Lets jump into the code straightaway.

Let’s start with the Authentication service. Since we are dealing only with interceptors we will be hard coding the JWT token and assume that the user is already logged in. We will store the JWT token in localstorage after the user is logged in and we will retrieve the token from the localstorage when we need it.

#angular8 #angular #http

Angular8 HTTP Interceptors
6.90 GEEK