Angular 2 - Dynamically find base url to use in the http requests (services)

11,724

Solution 1

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

Solution 2

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

Share:
11,724
Sojye
Author by

Sojye

Updated on June 24, 2022

Comments

  • Sojye
    Sojye almost 2 years

    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
    Sojye about 8 years
    I will try to implement your second example in my next solution :)
  • niaomingjian
    niaomingjian over 7 years
    In practice, is this the best way to define the base url?
  • Tim Gautier
    Tim Gautier over 7 years
    You can't just append to url in the request function as though it's always a string. It might be a Request object.
  • Elec
    Elec over 7 years
    Is this solution work with POST method? and why your second solution still have get method even it has request though?