时间:2022-03-17 09:52:17 | 栏目:AngularJS | 点击:次
如下所示:
//方案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] };