角2 - 动态发现基本URL中的http请求使用(服务) [英] Angular 2 - Dynamically find base url to use in the http requests (services)
问题描述
我不知道是否有获得基本URL,在HTTP请求使用的一个动态的方式?
I'm wondering if there is a dynamic way of getting the base url, to use in the http requests?
有没有获得 http://192.123.24.2:8080 动态?
Is there any way of getting the http://192.123.24.2:8080 dynamically?
public getAllTickets() {
this._http.get('http://192.123.24.2:8080/services/', {
method: 'GET',
headers: new Headers([
'Accept', 'application/json',
'Content-Type', 'application/json'
])
})
所以,我我的要求看起来是这样的:
So, I my request would look something like:
public getAvailableVersions() {
this._http.get('../services', {
method: 'GET',
headers: new Headers([
'Accept', 'application/json',
'Content-Type', 'application/json'
])
})
我正在寻找一种方式来不必硬code的URL REST调用。或者是有一个与URL一个全局变量的唯一选择?
I'm looking for a way to not having to hard code the URL for the REST calls. Or is the only option to have a global variable with the URL?
谢谢!
推荐答案
通过Angular2版本2.0.0-beta.6,可以覆盖合并
法
With version 2.0.0-beta.6 of Angular2, you can override the merge
method
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';
export class CustomRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'http://192.123.24.2:8080' + options.url;
return super.merge(options);
}
}
您可以用这种方式注册该类:
You can register this class this way:
bootstrap(AppComponent, [HTTP_PROVIDERS,
provide(BaseRequestOptions, { useClass: CustomRequestOptions })
]);
另一种方法可以延长HTTP对象在请求URL的基本URL的开头添加。
Another approach could be to extend the HTTP object to add at the beginning of the request URL a base URL.
首先,你可以创建一个扩展一个类 HTTP
一个具有的baseUrl
属性:
First you could create a class that extends the Http
one with a baseUrl
property:
@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
this.baseUrl = 'http://192.123.24.2:8080';
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return super.request(this.baseUrl + url, options).catch(res => {
// do something
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return super.get(this.baseUrl + url, options).catch(res => {
// do something
});
}
}
如下所述
和注册它:
and register it as described below:
bootstrap(AppComponent, [HTTP_PROVIDERS,
new Provider(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]);
这篇关于角2 - 动态发现基本URL中的http请求使用(服务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!