5

I'm wondering if there is a dynamic way of getting the base url, to use in the http requests?

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

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?

Thanks!

Sojye
  • 175
  • 2
  • 3
  • 9

4 Answers4

3

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

Another approach could be to extend the HTTP object to add at the beginning of the request URL a base URL.

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]
  })
]);
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I will try to implement your second example in my next solution :) – Sojye Mar 16 '16 at 13:37
  • 1
    You can't just append to url in the request function as though it's always a string. It might be a Request object. – Tim Gautier Jan 11 '17 at 17:14
  • Is this solution work with POST method? and why your second solution still have get method even it has request though? – Elec Jan 30 '17 at 05:08
3

You can create a file with your credentials

credentials.ts

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

And import it into your file

import {credentials} from 'credentials'

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

And with that you can handle dev/prod credentials

Raphael
  • 1,708
  • 13
  • 11
0

you can get your application context root as below

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

-2
import {LocationStrategy} from 'angular2/router';

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

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567