Search code examples
angular

Angular 2. Http calls to an "api" subdomain


The following example makes a regular call to http://example.com/api/products

makeApiCall(): Observable<ICall> {
    return this.http.post<ICall>('/api/products', {}, {})
}

For architectural reason, I need to make calls on 'api' subdomain (http://api. example.com/products)

How would I construct a call in such cases?
Please note, I would not hardcode 'example.com' anywhere.


Solution

  • I would suggest you to add the base url i.E. https://api.example.com to the enviroment varables. If that's not an option you might can do it like this:

    const baseUrl = document.location.protocol + '//api.' + document.location.hostname;
    return this.http.post<ICall>(baseUrl+'/api/products', {}, {})