Before knowing why it is best to manage , we will know the basics
Table of Contents
What is an angular interceptor?
It is an extension of the Angular framework, which helps us to handle our HTTP requests in an elegant way. This is to avoid writing many lines of code in our front end.
In Angular, we need to use HttpClient to handle our HTTP requests, which we usually do in the following way:-
const httpOptions = {
headers: new HttpHeaders().set(‘Content-Type’, ‘application/json’)
};
const request = new HttpRequest(url, httpOptions);
const response = await this.httpClient.request(request);
response.json().subscribe(res => console.log(res));
So, if you see the above code, we are using http client to handle our HTTP request, and we are subscribing to the http response to get the JSON response.
The above code will work for the GET request only, but if you need to use any other HTTP method, you need to write extra lines of code.
Angular interceptors are the solution to this issue. With the help of interceptors, we can make our front-end code more efficient and clean.
So,
What is an interceptor?
In Angular, an interceptor is a class that is used to intercept the request and response. You can request as per your requirements. For example, you can make the request as a POST, DELETE, PUT, etc.
Interceptors are the best way to make your Angular app code cleaner and simple.
What is the difference between a service and an interceptor?
Let us understand the difference between a service and an interceptor. A service is a class that is used to share data across components. The services are also responsible for communicating with the server.
Interceptors are the extension of the Angular service. They are used to make the request and responses.
For example:
@Injectable()
export class InterceptionService {
private url: string = ‘http://www.nseindia.com/content/historical/equities/’
constructor(private httpClient: HttpClient) {}
getData(url) {
return this.httpClient.get(this.url).pipe(
map((response: Response) => response.json())
);
}
}
This is the sample interceptor code.
Interceptors are used to handle the response and make it a clean and straightforward way.
Interceptors in Angular
There are two types of interceptors in Angular:
1. before request
2. after the response
1. before request
An interceptor is used to request before the request is made.
An example of the before request interceptor is as follows.
import { Injectable } from ‘@angular/core’;
import { HttpEvent, HttpHandler, HttpInterceptor,
Angular Interceptor Development
Angular Interceptor development is one of the essential features of Angular. This is because it provides security and prevents cross-site request forgery. It is also called CORS or XSRF. It can also be used for authentication.
- Angular interceptor is a feature provided by Angular to prevent cross-site request forgery (XSRF) and Cross-origin resource sharing (CORS). It can be used for different purposes, such as authorization, authentication, etc.
- The best way to use Angular interceptor is to add it to the top of the page or the application. This will prevent the application from being vulnerable to XSRF and CORS attacks.
- Angular interceptor is a feature provided by Angular to prevent cross-site request forgery (XSRF) and Cross-origin resource sharing (CORS). It’s a special HTTP header that is sent to the server with every request.
- This header has the name XSRF-TOKEN and it contains a value which can be used to identify the origin of the request. If the title is missing or if its value is different from the one sent by the browser, then an error message will be shown to the user.
How does it work?
It can perform cross-site request forgery (CSRF) prevention and Cross-origin resource sharing (CORS), which means that it checks the authenticity of the user and ensures that they are not from another website.
It also ensures that the request is from the authorized website, not a malicious site.
Why is it important?
It is essential to have a secure website, and it is an easy way to ensure that a user is not from a malicious site.
Advantages of using Angular interceptor:
• It makes sure that the request is coming from the exact origin and it is coming from the right source.
• It can be used for different purposes like login, logout, authorization, authentication, etc.
• It is a simple and effective way to ensure the user is authentic.
• It also checks if the request is coming from a trusted domain.
• It is also helpful to make sure that the request is coming from a trusted source and it is coming from the right source.
How to make use of Angular interceptor?
To make use of this feature, you need to include the following code in your index.html page:
Then add the following code:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from ‘@angular/common/http’;
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor ()
Create an Interceptor
The goal is to include the JWT sent to local storage as an Authorization header in any HTTP request.
When you’re working with interceptors, you need to inject the proper object, and a common mistake is to create an injectable class,
- // src/app/auth/token.interceptor.tsimport { Injectable } from ‘@angular/core’;
- import {
- HttpRequest,
- HttpHandler,
- HttpEvent,
- HttpInterceptor
- } from ‘@angular/common/http’;
- import { AuthService } from ‘./auth/auth.service’;
- import { Observable } from ‘rxjs/Observable’;@Injectable()
- export class TokenInterceptor implements HttpInterceptor { constructor(public auth: AuthService) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
- request = request.clone({
- setHeaders: {
- Authorization: `Bearer ${this.auth.getToken()}`
- }
- }); return next.handle(request);
- }
- }
Anyone who wants to intercept requests will need to implement the Interceptor interface.
The new class will have a method called “intercept” with parameters “HttpRequest” and “HttpHandler”.
Interceptors enable us to modify outgoing HTTP Requests, but we cannot change the original HTTP Request that will arrive at the destination server.
We have to clone the original request and set any headers we want. When we do that, we can make changes.
First of all, let’s add the authorization header to each request by adding this line of code to our server: this.httpHeaders = new HttpHeaders(); this.httpHeaders.
Intercepting the call. Handling means you are handing over control to the next interceptor.