We have different types of microservice running on different machines and I would like to connect to them. But since all microservice is having their own headers I need to pass them accordingly in my Angular application.
I have written an interceptor to intercept and attach the headers and send the request to server as shown below
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
export class JwtInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${----token-----}`,
'api-version': '1.0.0'
}
});
return next.handle(req);
}
}
but I would like to set respective headers based on the type of microservice that I would like to connect with.
What would be the best possible approach to handle this ?
At a very generic level, we do something to what @riorudo suggested in his comment.
We set up an array of configuration object conceptually something like this:
[
{ method: 'GET', urlToIntercept: '/something'},
{ method: 'POST', urlToIntercept: '/somethingElse' }
// etc.. etc...
]
You could hard code this as a config in the interceptor or pass it in as a service.
The interceptor code can do something along the lines of:
if (interceptableMethodList.find(element => request.urlToIntercept.includes(element.url) && request.method.toLowerCase() === element.method)) {
// add header
}