Angular custom header in interceptor

Viewed 1818

I am working on an Angular 9 application with a request interceptor, which is supposed to send the server the UI version that is making the request.

Because this data is required for requests, I added it in an interceptor. The problem is that it seems that it is not working correctly.

Here is my interceptor code:

@Injectable()
export class VersionInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const version = request.clone({ setHeaders: { 'App-version':  environment.UIversion } });
    return next.handle(version);
  }
}

and this in may app.module providers

providers: [
    { provide: Http, useClass: AuthenticatedHttpService },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorHttpInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: VersionInterceptor, multi: true },
    { provide: APP_BASE_HREF, useValue: environment.baseurl },
]

But my requests don't have the header "App-version"

enter image description here

only one request has it and it fails (But if I remove the interceptor, this request works fine)

enter image description here

Is there a standard to send my ui version in headers? If not, is there any way to add a custom header name to send my ui version to the server?

Thank you very much

1 Answers

I found that I also couldn't pass custom headers. However, I could pass custom parameters on the call which were available in the interceptor.

In Service pseudo code

constructor(private http: HttpClient) {}

getMethod(): Observable<Type> {
  let params = { "X-custom-param": "true" };
  let options = { params: params };
  this.http.get<Type>(url, options);
} 

In Interceptor

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(request).pipe(
    tap((e) => {}),
    catchError((error: HttpErrorResponse) => {
      let custom = request.params.get("X-custom-param");
Related