0

I must be approaching this from a false perspective, but here is the problem. I have an async validation directive which uses HttpClient to validate something with the backend. It is almost independent apart from one critical thing – it needs correct HTTP headers to pass authentication on the server side. This is how the constructor looks:

constructor( 
    private http: HttpClient,
    private auth: AuthService,
    @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]
) { 
    this.valueAccessor = valueAccessors.find( x => x.constructor === DataTextInputComponent) as DataTextInputComponent;
}

This one auth service has the correct headers, which will then be used with the request.

I have recently split my project into libs and apps with Nx and want to use this directive in a different context, where the headers and the request url are different. How do I achieve this?

3
  • The only idea which seems workable so far is to have yet another service with the only goal to keep the headers (get, set). I can then inject this service into the AuthService as well as any other service and get/set http headers quasi independently... ヽ( ツ )丿 Commented Nov 11, 2019 at 19:32
  • So let me get this right, you have a directive and you want to pass it something. In this case the something is some headers. But you have the problem of having this directive in a different module than the one you will consume it in ( I assume the directive is in libs and you want to use it in apps ) correct? Commented Nov 12, 2019 at 8:21
  • Correct. I want to pass a value to this directive, which then would check it over http; the request needs the headers. For now the headers are kept within a service in a different app. For a different app I'd have different headers, but I would make the same http request. Commented Nov 12, 2019 at 8:25

1 Answer 1

2

Now I understand your problem, I can confidently recommend you to use http interceptors. Those will essentially act as middleware and will modify the request before the call is done. You can provide interceptors on module level, which will ensure you can have different interceptors per module.

This will also ensure you adhere to the single responsibility principle, as this directive can do the validation calls without worrying about setting the correct headers.

Here is an example of an http interceptors implementation in angular v5

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.