Adding Token Interceptors to Authenticate Requests in Angular
Learn to create interceptors in Angular.
Overview of interceptors in Angular
Interceptors are a special type of Angular service that enables us to handle incoming and outgoing HTTP requests and HTTP responses using the HttpClient
. Angular interceptors use the intercept()
method to configure any HTTP request or response. The intercept()
method takes in two parameters and then returns an observable, as seen below:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
The req
parameter helps handle the outgoing request object, while the next
parameter handles the next interceptor in the chain or the backend. If no interceptors remain in the chain by calling next.handle(tokenizedReq)
, the intercept()
method returns an observable event stream.
The Angular interceptor can be used to perform several utility functions, some of which include:
- Headers configuration
- In-app notifications
- Error handling
- Authentication
- Setting loaders
Creating an Angular interceptor
To create an Angular interceptor, we’ll use the Angular CLI by running the command below at the root of our project:
ng generate interceptor auth/token
Inside the auth
folder, the following files are generated by the Angular CLI:
token.interceptor.spec.ts
token.interceptor.ts
Get hands-on with 1200+ tech skills courses.