Search code examples
angularangular-http-interceptors

How to intercept the response in angular 4 with HttpInterceptor


I do have the following Interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private tokenService: TokenService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.tokenService.getToken();

    if (token) {
      const authReq = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });

      return next.handle(authReq);
    }

    return next
      .handle(req)
//
      .getSomehowTheResponse()
      .andSaveTheTokenInStorage()
      .andPropagateNextTheResponse()
  }
}

And I want to save the token from the response header in local storage, all the tutorials are showing how to intercept the request, but not very clearly the response.


Solution

  • next.handle(req) returns an observable so you can subscribe to it:

    return next.handle(req).map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response and headers you want
        event.headers
        event.body
      }
      return event;
    })
    

    To learn more about mechanics behind interceptors read: