如下所示:
//方案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]
};
以上这篇angular2实现统一的http请求头方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持天达云。