Angular 2 - 动态查找要在http请求(服务)中使用的基本URL

时间:2016-02-18 07:04:05

标签: rest http url service angular

我想知道是否有动态方式获取基本网址,以便在http请求中使用?

有没有办法动态获取 http://192.123.24.2:8080

public getAllTickets() {
    this._http.get('http://192.123.24.2:8080/services/', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })

所以,我的请求看起来像是:

public getAvailableVersions() {
    this._http.get('../services', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })  

我正在寻找一种不必硬编码REST调用URL的方法。或者是具有URL的全局变量的唯一选择?

谢谢!

4 个答案:

答案 0 :(得分:3)

使用Angular2的2.0.0-beta.6版本,您可以覆盖merge方法

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);
  }
}

您可以这样注册此课程:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    provide(BaseRequestOptions, { useClass: CustomRequestOptions })
]);

另一种方法可以是扩展HTTP对象,以在请求URL的开头添加基本URL。

首先,您可以使用Http属性创建一个扩展baseUrl的类:

@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
    });
  }
}

并按如下所述进行注册:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

答案 1 :(得分:3)

您可以使用凭据创建文件

credentials.ts

export var credentials = {
  client_id: 1234,
  client_secret: 'secret',
  host: 'http://192.123.24.2:8080'
}

并将其导入您的文件

import {credentials} from 'credentials'

public getAllTickets() {
    this._http.get(credentials.host + '/services/', {
        method: 'GET',
        headers: new Headers([
            'Accept', 'application/json',
            'Content-Type', 'application/json'
        ])
    })

然后你可以处理dev / prod凭证

答案 2 :(得分:0)

您可以按如下所示获取应用程序上下文根

this.baseURL = document.getElementsByTagName('base')[0] .href;

答案 3 :(得分:-2)

import {LocationStrategy} from 'angular2/router';

constructor(private locationStrategy:LocationStrategy) {
  console.log(locationStrategy.prepareExternalUrl('xxx'));
}

另见https://github.com/angular/angular/blob/1bec4f6c6135d7aaccec7492d70c36e1ceeaeefa/modules/angular2/test/router/path_location_strategy_spec.ts#L88