在 Angular 中使用不同服务的指令 [英] Using directive with different services in Angular

查看:36
本文介绍了在 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?

推荐答案

现在我明白你的问题了,我可以自信地推荐你使用 http 拦截器.这些本质上将充当中间件,并在调用完成之前修改请求.您可以在模块级别提供拦截器,这将确保每个模块可以有不同的拦截器.

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.

这是 angular v5

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

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