Search code examples
angularhttpjwtmean-stackangular-http-interceptors

Angular interceptor executed before http request


I'm working with a MEAN app and I'm having problems with the token interceptor. It is supposed to apply the headers after an user is logged in with this code:

 intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const token = localStorage.getItem('token');
    let req = request;
    if (token) {
      req = request.clone({
        setHeaders: {
          authorization: `Bearer ${token}`
        }
      });
    }
 }

However, I debugged the code and it is being executed before the login calls the api (so there's no login, no token, no user data, etc.). Thus it's useless, because I need the token in order to set the headers as the code shows.


Solution

  • You can combine it with a pipe and tap (or any other RxJs operators) to operate on a response call before it gets to your service.

    logging-request-and-response-pairs

    intercept(req: HttpRequest<any>, next: HttpHandler) {
           // change req here before being send
               
            return next.handle(req)
              .pipe(
                tap(
                  // to access data, or use map to manipulate it.
                )
              );