angular2实现统一的http请求头方法
如下所示:
//方案1:能用,但token信息不能写在服务中,应该用全局变量替代,而且还得考虑参数复合问题。 @Injectable() export class DefaultRequestOptions extends BaseRequestOptions { constructor() { super(); this.headers.set('Content-Type', 'application/json'); } } export const requestOptionProvider = {provide: RequestOptions, useClass: DefaultRequestOptions}; //方案2:能用,比较正规的实现,但以后请求就只能用myHttp对象了,而且还要考虑参数复合问题。 export class myHttp extends Http { defaultHeaders = new Headers({ 'Content-Type': 'application/json' }); constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private appInitService: AppInitService) { super(_backend, _defaultOptions); } get(url: string, options?: RequestOptionsArgs): Observable<Response> { let optionBuf = new RequestOptions({ headers: this.defaultHeaders, params: {'token': this.appInitService.token} }); //here extend options; return super.get(url, optionBuf); } } export function myHttpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, appInitService: AppInitService): myHttp { return new myHttp(xhrBackend, requestOptions, appInitService); // 创建myHttp对象 } export const myHttpProvider = { provide: myHttp, useFactory: myHttpFactory, deps: [XHRBackend, RequestOptions, AppInitService] };
相关推荐
shayuchaor 2020-06-25
hygbuaa 2020-04-22
sicceer 2020-04-18
hygbuaa 2020-02-12
sicceer 2020-01-29
无材可去补苍天 2013-05-14
OwenJi 2020-01-17
用不完的好奇心 2020-01-14
似水流年梦 2020-01-03
knightwatch 2019-11-05
88407013 2019-10-08
besily 2018-08-20
82443365 2015-01-14
87193155 2012-12-30
81530694 2011-11-16
89520292 2011-09-23
yanghui0 2011-01-19
87570495 2019-06-28