我看到两种方法:
原文链接:https://www.f2er.com/angularjs/140865.html>选项#1:使用BaseRequestOptions类
您可以扩展此类,并将标题设置为用于每个请求:
@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类本身
您还可以扩展Http类并设置所需的标题,如下所述:
@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] }) ]);
希望它能帮助你,蒂埃里