angular2实现统一的http请求头方法

作者:袖梨 2022-06-25

如下所示:

//方案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 {
  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]
};

相关文章

精彩推荐