我需要在用户登录后为每个后续请求设置一些授权标头.
要为特定请求设置标头,
import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);
// HTTP POST using these headers
this.http.post(url, data, {
headers: headers
})
// do something with the response
Run Code Online (Sandbox Code Playgroud)
但是以这种方式为每个请求手动设置请求标头是不可行的.
如何在用户登录后设置标头集,并在注销时删除这些标头?
我想Content-type: application/json在我对Angular2中后端的所有请求中设置标题.我在我的主app.js文件中使用它.
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('/')
])
Run Code Online (Sandbox Code Playgroud)
我期望Http使用新内容类型的所有用途,但此代码仍设置为内容类型text/plain
saveMaster (master) {
return this.http
.put(`${config.API_URL}/masters/${master._id}`, JSON.stringify(master))
.map(res => res.json())
}
Run Code Online (Sandbox Code Playgroud)
我必须手动设置每个请求的标头,以使其正常工作.难道我做错了什么?
注意:我想要全局设置标题选项,而不必像每个请求类型一样设置它,就像在此解决方案中找到的那样.