如何设置默认HTTP标头在Angular2? [英] How to set default HTTP header in Angular2?
本文介绍了如何设置默认HTTP标头在Angular2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何使用的页眉类。
有没有办法做到这一点对于所有 HTTP调用?
Is there a way to do it for all HTTP calls?
推荐答案
我看到两种方法可以做到这一点:
I see two ways to do that:
- 选项#1 :使用
BaseRequestOptions
类
- Option #1: use the
BaseRequestOptions
class
您可以扩展此类,并设置用于每个请求头:
You could extend this class and set the header to use for each request:
@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions{
headers:Headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
}
和如下所述其注册:
bootstrap(AppComponent,[
HTTP_PROVIDERS,
provide( RequestOptions, { useClass: DefaultRequestOptions })
});
- 选项#2 :延长
HTTP
类本身 - Option #2: extend the
Http
class itself
您还可以扩展 HTTP
类,并设置你想要它的标题,描述如下:
You could also extend the Http
class and set the headers you want in it, as described below:
@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
// Add headers into options
(...)
return super.get(url, options);
}
(...)
}
和如下所述其注册:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]);
希望它可以帮助你,
蒂埃里
Hope it helps you, Thierry
这篇关于如何设置默认HTTP标头在Angular2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文