Interceptors give a system to block or potentially transform active requests or incoming reactions. They are basically the same as the idea of center product with a structure like Express, aside from the front-end.
Ways to use Interceptors in Angular
1- URL
We could, for instance, need to change HTTP to HTTPS.
It’s essentially as simple as cloning the solicitation and supplanting http://with https://simultaneously. Then, at that point, we send the cloned, HTTPS solicitation to the following overseer.
In the model, we set the URL with HTTP, yet when we check the request, we can see that it changed to HTTPS.
const url = “http://jsonplaceholder.typicode.com/todos/1″;
this.response = this.http.get(url);
Automatic HTTPS, for what reason is this not higher up? Indeed, regularly you would set up these things on your web server. Or on the other hand if you have any desire to switch among HTTP and HTTPS being developed you could utilize the CLI:
ng serve -ssl
At the same time, you can change a little more of the URL and say it an API prefix interceptor:
req.clone({
url: environment.serverUrl + request.url
});
Or you could again do it with the CLI:
ng serve — serve-path=<path> — base-href<path>/
2- Set Headers
We can do a lot by altering headers. Some are:
- Authentication
- Caching behaviour; for instance, If-Modified-Since
- XSRF protection
const modified = req.clone({
setHeaders: { “X-Man”: “Wolverine” }
});
return next.handle(modified);
3- Converting response
At the point when the API returns a configuration we disagree with, we can utilize an angular HTTP interceptor to organize it the manner in which we like it. This could be changing over from XML to JSON or like in this model property names from PascalCase to camelCase. On the off chance that the back-end couldn’t care less about JSON/JS shows we can utilize an interceptor to rename all the property names to camelCase.
return next.handle(req).pipe(
map((event: HttpEvent<any>) => {
if (event instanceofHttpResponse) {
let camelCaseObject = mapKeys(event.body, (v, k) => camelCase(k));
const modEvent = event.clone({ body: camelCaseObject });
return modEvent;
}
})
);