I am trying to modify response header or an API request that goes from my Angular Application. What I have done is I have created a RequestTracker interceptor which extends HttpInterceptor and adds Correlation-Id to request header. What I want is the same Correlation-Id to be part of the response header. I tried the below interceptor but it isn't working for me. Is there anything I am missing?
import * as uuid from 'uuid';
import {
HttpEvent,
HttpHandler,
HttpHeaders,
HttpInterceptor,
HttpRequest,
HttpResponse
} from '@angular/common/http';
import { filter, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class RequestTracker implements HttpInterceptor {
intercept(
httpRequest: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const correlationId = uuid.v4();
const httpRequestClone = httpRequest.clone({
setHeaders: {
'Correlation-Id': correlationId
}
});
return next.handle(httpRequestClone).pipe(
filter((response) => response instanceof HttpResponse),
map((response: HttpResponse<any>) => {
const modifiedResponse = response.clone({
headers: response.headers.set('Correlation-Id', correlationId)
});
return modifiedResponse;
})
);
}
}
In Request Headers, the Correlation-Id is getting appended but not in Response Headers.
The response that you have posted, is from the network tab and it refers to the response sent from the server. You are attaching the header once Angular starts processing that response. So it won't be shown in the network tab. Try logging the response inside the code. And correlationId will be part of the response header.