在Angular中将指令与其他服务一起使用 [英] Using directive with different services in Angular

查看:70
本文介绍了在Angular中将指令与其他服务一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从错误的角度来解决这个问题,但这是问题所在.我有一个异步验证指令,该指令使用HttpClient来验证后端的内容.除了一件关键的事情,它几乎是独立的–它需要正确的HTTP标头才能在服务器端通过身份验证.这是构造函数的外观:

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;
}

auth服务具有正确的标头,然后将其与请求一起使用.

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

我最近用Nx将我的项目分成了libsapps,并希望在不同的上下文中使用此伪指令,其中标头和请求URL不同.我该如何实现?

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?

推荐答案

现在,我了解您的问题,我可以自信地建议您使用

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.

以下是角度v5

这篇关于在Angular中将指令与其他服务一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆