我正在尝试为我的所有角度2 http请求设置基本网址.以下是我的申请的基本设置.
class HttpOptions extends BaseRequestOptions {
url:string = "http://10.7.18.21:8080/api/";
}
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(RequestOptions, {useClass: HttpOptions})
]);
export class AppComponent {
users:Array
constructor(private http: Http) {
http.get("/users")
.subscribe(res => this.users = res.json());
}
}
请求不会发送到http://10.7.18.21:8080/api/users,正如我对我的配置所期望的那样.而是将请求发送到http:// localhost:8000/users.
如何在角度2应用程序中为http请求设置基本URL?
我正在使用Angular 2.0.0-beta.0.
对于角度4.3+和@ angular/common/http
拦截器很简单
@Injectable()
export class ExampleInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const url = 'http://myurl.com';
req = req.clone({
url: url + req.url
});
return next.handle(req);
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
HttpClientModule,
...
],
providers: [
AppComponent,
{ provide: HTTP_INTERCEPTORS, useClass: ExampleInterceptor, multi: true }
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
编辑:HttpClient和HttpInterceptor在Angular 4.3中引入
更新:请参阅Angular 4的@vegazz答案.
对于Angular 2.2.1,以下内容应为web api base url的前缀,并表示较小的占用空间:
import {Request, XHRBackend, XHRConnection} from '@angular/http';
@Injectable()
export class ApiXHRBackend extends XHRBackend {
createConnection(request: Request): XHRConnection {
if (request.url.startsWith('/')){
request.url = 'http://localhost:3000' + request.url; // prefix base url
}
return super.createConnection(request);
}
}
在app.module.ts中注入提供者:
providers: [
{ provide: XHRBackend, useClass: ApiXHRBackend }
]
用法示例:
this._http.post('/api/my-route', {foo: 'bar'})
.map(res => res.json())
它似乎涵盖了所有方法(GET,PUT,POST,......)
来自RC5的Angular标记HTTP_PROVIDERS
为已弃用且试图将其移入@NgModule
,上述解决方案并不真正适用,因此作为其文档.我交叉了几个其他的答案,找到了实现基本网址的方法,希望这对其他人有帮助.
基本的想法是,我们不是在引导程序中做事情,而是将事情转移到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以外的请求类型,则前一种方法无法将baseurl注入请求中.这是因为Angular2产生新的RequestOptions
比其他this._defaultOptions
其合并方法是不是被我们CustomRequestOptions覆盖.(请参阅此处的源代码).
因此super.merge(...)
,我没有在CustomRequestOptions合并方法的最后一步返回,而是生成了一个新实例,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方法.希望这是有帮助的.
在Angular 2.0.0-beta.6中你可以通过覆盖'merge'来实现这一点
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';
export class ApRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'http://10.7.18.21:8080/api' + options.url;
return super.merge(options);
}
}
在看看代码源后BaseRequestOptions
,RequestOptions
与Http
类:
base_request_options.ts
http.ts
看起来该url
属性对应于默认URL,但不是URL的前缀.
为了实现你的用例,我建议在http对象前放一个服务然后注入服务.像这样的东西:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
@Injectable()
export class HttpClient {
http: Http;
urlPrefix: string;
constructor(http: Http) {
this.http = http;
this.urlPrefix = 'http://...';
}
get(url) {
return this.http.get(this.urlPrefix + url);
}
post(url, data) {
return this.http.post(this.urlPrefix + url, data);
}
}
和
import {HttpClient} from './http-client';
export classMyComponent {
constructor(httpClient: HttpClient) {
this.httpClient = httpClient;
}
handleSomething() {
this.httpClient.post(url, data)
).subscribe(...);
}
}
也就是说,这可能是Angular2本身的贡献;-)
希望它对你有帮助,蒂埃里
不同的方法:在开发过程中在localhost中运行您的应用程序时,请考虑配置代理。
proxy.conf.json
{
"/api/**": {
"target": "http://10.7.18.21:8080/",
"secure": false,
"logLevel": "debug"
}
}
更多:链接