如何在 Angular2 中设置全局自定义标头? [英] How do you set global custom headers in Angular2?
本文介绍了如何在 Angular2 中设置全局自定义标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I want to set the header Content-type: application/json
in all my requests to my backend in Angular2. I use this in my main app.js
file.
let headers = new Headers({
'Content-Type', 'application/json'
})
class MyOptions extends BaseRequestOptions {
headers: headers
}
bootstrap(App, [
provide(RequestOptions, {useClass: MyOptions}),
ROUTER_BINDINGS,
HTTP_PROVIDERS,
bind(APP_BASE_HREF).toValue('/')
])
I'm expecting all uses of Http
to use the new content-type, but this code still has the content-type set to text/plain
saveMaster (master) {
return this.http
.put(`${config.API_URL}/masters/${master._id}`, JSON.stringify(master))
.map(res => res.json())
}
I have to manually set the headers for each request to get it work correctly. Am I doing something wrong?
Note: I want to set a header option globally, not have to set it with every request type like is found in this solution.
解决方案
- Change
MyOptions
to:
class MyOptions extends RequestOptions {
constructor() {
super({
method: RequestMethod.Get,
headers: new Headers({
'Content-Type': 'application/json',
'X-Some-Header': 'some-content'
});
});
}
}
- Put
provide(RequestOptions, {useClass: MyOptions})
AFTERHTTP_PROVIDERS
(otherwise defaultBaseRequestOptions
will be used instead of yourMyOptions
).
bootstrap(App, [
// ...
HTTP_PROVIDERS,
provide(RequestOptions, {useClass: MyOptions}) // <- after HTTP_PROVIDERS!!!
])
See this plunk
这篇关于如何在 Angular2 中设置全局自定义标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文