0

I would like to add an if statement to the following logic inside of my HttpInterceptor:

const authToken = this.auth.getAuthorizationToken();

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

I would like to check if authToken exists prior to updating the headers with the authToken. I am pretty sure this is either a syntax thing or there is another way to set the headers property of req.clone() in a code block or something.

Here is my best shot at our but I feel like there is a better way to do it:

let authReq: HttpRequest<any> = req;

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

1 Answer 1

1

You are on the right track. You need to modify the request if the token exist or leave it unchanged if there is no token. Example:

intercept(
  req: HttpRequest<any>,
  next: HttpHandler,
): Observable<HttpEvent<any>> {
  const authToken = this.auth.getAuthorizationToken();

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

  return next.handle(req);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I know this is a bit off topic, but do you have an idea of why services that make http requests using HttpClient in lazy loaded modules are not going into the interceptor? I added the interceptor to the core.module.ts of my site which is imported into app.module.ts. Components and Modules imported directly into app.module use the interceptor but lazy loaded modules in app.routing do not.
It sounds like you are experience this: github.com/angular/angular/issues/20575. Make sure you are only importing HttpClientModule once per app
I saw that post and already checked it. I will double check again. The only place it is being imported and exported is in my shared.module.ts which is basically imported in many other child modules.. hmm maybe that's it. If shared module is imported in multiple places and has an export of HttpClientModule do you think that's my prob? I feel like that defeats the purpose of a shared module exporting common modules used throughout the system.
I believe that would be the issue. You should import the HttpClientModule once in either the AppModule or the CoreModule if you have one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.