【问题标题】:Angular 2 - Dynamically find base url to use in the http requests (services)Angular 2 - 动态查找要在 http 请求(服务)中使用的基本 url
【发布时间】:2016-05-30 05:34:09
【问题描述】:

我想知道是否有一种动态的方式来获取基本 url,以便在 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 中使用全局变量?

谢谢!

【问题讨论】:

  • 这是您要找的东西吗:window.location.host
  • 谢谢!!这样就解决了。
  • 但是,我认为在我的下一个解决方案中,我将设置一个全局变量。当我实现它时,我会在这篇文章中添加评论:)

标签: rest http url service angular


【解决方案1】:

使用 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。

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

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

【讨论】:

  • 我将尝试在我的下一个解决方案中实现您的第二个示例 :)
  • 您不能只是附加到请求函数中的 url,就好像它始终是一个字符串一样。它可能是一个 Request 对象。
  • 此解决方案是否适用于 POST 方法?以及为什么您的第二个解决方案即使有请求仍然有 get 方法?
【解决方案2】:

您可以使用您的凭据创建文件

凭据.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'
        ])
    })

这样您就可以处理开发/产品凭据

【讨论】:

  • 在实践中,这是定义基本 url 的最佳方式吗?
【解决方案3】:
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

【讨论】:

    【解决方案4】:

    你可以得到你的应用程序上下文根如下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多