在这种情况下,扩展BaseRequestOptions可能会有很大帮助。看看下面的代码:
import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http';
import {AppCmp} from './components/app/app';
class MyRequestOptions extends BaseRequestOptions {
constructor () {
super();
this.headers.append('My-Custom-Header','MyCustomHeaderValue');
}
}
bootstrap(AppCmp, [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(RequestOptions, { useClass: MyRequestOptions })
]);
这应该包括'My-Custom-Header'在每个调用。
更新:
为了能够在任何时候改变头,而不是上面的代码,你也可以使用下面的代码来添加一个新的头:
this.http._defaultOptions.headers.append('Authorization', 'token');
要删除就可以了
this.http._defaultOptions.headers.delete('Authorization');
还有另一个函数,你可以用来设置值:
this.http._defaultOptions.headers.set('Authorization', 'token');
上述解决方案在typescript上下文中仍然不完全有效。_defaultHeaders是受保护的,不应该这样使用。我会推荐上面的解决方案作为快速修复,但从长远来看,更好的方法是编写自己的包装器来处理http调用,它也可以处理身份验证。以auth0为例,它更好、更简洁。
https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts
Update - June 2018
I see a lot of people going for this solution but I would advise otherwise. Appending header globally will send auth token to every api call going out from your app. So the api calls going to third party plugins like intercom or zendesk or any other api will also carry your authorization header. This might result into a big security flaw.
So instead, use interceptor globally but check manually if the outgoing call is towards your server's api endpoint or not and then attach auth header.