0

I am using a http interceptor in my angular project. I have a variable that I want to change at runtime that I can add various headers to. The basic setup of my interceptor is below

export class HeaderInterceptor implements HttpInterceptor {
  public additionalHeaders: KeyValuePair[]


  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {.....
}

I am initializing this in my module as follows.

 providers: [{ provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, deps: [AppConfigProvider, Router], multi: true }]

This all works fine but I cant think of a way to change the additionalHeaders property once the application is loaded. Is there a way to inject the interceptor into a component or perhaps a better way to do this altogether?

4
  • The point of an HttpInterceptor is to apply any rules you always want to apply to any http request. If there is a specific header you want to apply only in certain scenarios, those should go directly onto the construction of the http request. Commented Aug 5, 2019 at 18:55
  • I don't think adding headers for a component via an Interceptor is a good approach. Add the headers in the service for that component explicitly. Commented Aug 5, 2019 at 19:53
  • 1
    I dont agree, adding for example Authorization: bearer is common practice Commented Aug 5, 2019 at 19:55
  • In my case the interceptor is part of a framework used across multiple applications. One app needs different information in the header to another and the information within can change during the users session. Commented Aug 5, 2019 at 21:58

1 Answer 1

1

Instead of accessing the interceptor directly, why not have some form of state service or something that both services can interact with.

Your desired service can set some values and then your interceptor can read them, without the originating service needing to know if the existence of an interceptor at all.

Services can be injected into interceptor services just like any other.

Sign up to request clarification or add additional context in comments.

Comments

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.