Search code examples
angularhttphttpresponseinterceptorangular-services

How to use header from interceptor in my app


I have added a responseWithHeader to my HTTP request in my backend. I can see this is working correctly as it is appearing in my Network tab of Developer Tools.

I am using interceptor in Angular to handle HTTP Requests and Responses, but the issue I am having is as follows:

I have added the version number of my app as a header to the response, I need to then compare this version in the header to the version declared within my package.json. If the version in the response header is newer than the one in package.json, I want to show a `Snackbar`` prompting the user to refresh the page. However, I cannot figure out how to 'extract' the header value, and parse it to a service, which my app component can subscribe to.

Here is my interceptor method:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.cookieService.get('token');
    let headers = req.headers;
    if (token) {
      headers = headers.append('Authorization', token);
    }

    const authReq = req.clone({
      headers: headers
    });

    return next.handle(authReq).pipe(
        map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
              console.log(event.headers.get('x-web-frontend-version'));
            }
            return event;
        }));
  }

Any time I try to call a method, such as this.baseService.handleVersion(INSERT HEADER VALUE), the app throws errors. How can I parse this header to a service method?


Solution

    1. You need to get header "properly", solution here: Angular 2 http Observable request not returning response header
    2. Create kind of mediator service to keep version as Subject, and subscribe anywhere you need