简体   繁体   English

如何在HTTP请求上设置模块特定的自定义标头?

[英]How can I set module specific custom headers on a HTTP request?

I would like to be able to set a custom header on the HTTP requests my application triggers. 我希望能够在应用程序触发的HTTP请求上设置自定义标头。 This header must indicate from which submodule the request has been fired. 此标头必须指示从哪个子模块触发了请求。

I already tried creating an interceptor and a decorator (in each module) but both options are placed on the global angular $http service and thus overriding eachother. 我已经尝试创建一个拦截器和一个装饰器(在每个模块中),但是这两个选项都放在了全局的$ http服务上,因此彼此替代。

The only option that works is specifying the header when calling the $http service but that is not really what I want. 唯一有效的选项是在调用$ http服务时指定标头,但这并不是我真正想要的。 The goal is to write a interceptor or decorator on each module that catches all requests from that module, setting a header accordingly. 目标是在每个模块上编写一个拦截器或装饰器,以捕获来自该模块的所有请求,并相应地设置标头。

Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

Pretty sure this can't be solved just by separation using modules since as you've found the $http service is in the 'ng' module which is automatically included. 可以肯定的是,仅通过使用模块进行分离就无法解决此问题,因为您已经发现$ http服务位于自动包含的ng模块中。 When you inject $http you are getting the same instance that's defined in the 'ng' built-in module. 注入$ http时,您将获得与“ ng”内置模块中定义的实例相同的实例。

Your best bet is probably to write base classes that you use for two factory/service objects that each abstract away the actual calls and set the appropriate headers. 最好的选择可能是编写用于两个工厂/服务对象的基类,每个基类都抽象出实际的调用并设置适当的标头。 Nice basis for an API abstraction layer implementation here https://gist.github.com/jelbourn/6276338 API抽象层实现的良好基础在这里https://gist.github.com/jelbourn/6276338

what you can do is (what I had done) prefixed all the api paths with module names eg 'stk-api/abc/get', 'fu-api/xyz/get', etc.. and then in interceptor change the api path to remove the module part 'stk-' or 'fu-' and added the custom header as per the removed part or module name.. 您可以做的是(我所做的)为所有api路径加上模块名称,例如“ stk-api / abc / get”,“ fu-api / xyz / get”等。然后在拦截器中更改api删除模块部件'stk-'或'fu-'的路径,并根据删除的部件或模块名称添加了自定义标头。

I know its a workaround kind of solution, but did the job for me... 我知道这是一种解决方法,但为我做了工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM