Using directive with different services in Angular

三世轮回 提交于 2019-12-11 16:36:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/58746929/using-directive-with-different-services-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!