对于 Angular2 版本 2.2(截至 2016 年 12 月)
来自 RC5 的 Angular 将 HTTP_PROVIDERS 标记为已弃用并试图将内容移至 @NgModule,上述解决方案并不真正适用,因此他们的文档也是如此。我交叉引用了其他几个答案,并找到了实现基本 url 的方法,希望这对其他人有帮助。
基本思想是,我们不是在引导程序中做事情,而是将事情转移到AppModule。
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, RequestOptions } from '@angular/http';
import { CustomRequestOptions } from './customrequest.options';
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
HttpModule,
...
],
providers: [
{ provide: RequestOptions, useClass: CustomRequestOptions }
],
bootstrap: [ AppComponent ]
})
并将 CustomRequestOptions 移动到单独的可注入服务中
import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, RequestOptionsArgs } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'http://localhost:9080' + options.url;
return super.merge(options);
}
}
编辑 GET 以外的请求方法。
如果您尝试发送 GET 以外的请求类型,则之前的方法无法将 baseurl 注入请求中。这是因为 Angular2 生成了新的 RequestOptions 而不是 this._defaultOptions,其合并方法没有被我们的 CustomRequestOptions 覆盖。 (请参阅此处的source code)。
因此,我没有在 CustomRequestOptions 合并方法的最后一步返回 super.merge(...),而是生成了一个新的 CustomRequestOptions 实例,以确保以下操作仍然有效。
import { Injectable } from '@angular/core';
import { RequestOptions, RequestOptionsArgs } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends RequestOptions {
merge(options?: RequestOptionsArgs): RequestOptions {
if (options !== null && options.url !== null) {
options.url = 'http://localhost:9080' + options.url;
}
let requestOptions = super.merge(options)
return new CustomRequestOptions({
method: requestOptions.method,
url: requestOptions.url,
search: requestOptions.search,
headers: requestOptions.headers,
body: requestOptions.body,
withCredentials: requestOptions.withCredentials,
responseType: requestOptions.responseType
});
}
}
这也适用于 POST、PUT、DELETE 方法。希望这会有所帮助。