Javier Enríquez Javier Enríquez - 1 month ago 4x
HTTP Question

How do I make requests to API server without hardcoding the URL?

I'm trying to implement an app with angular 2 and need to make requests to my API server. However, I think it's a bad idea to hardcode the full URL in every request because it will change very likely. I took a look to this post:
Set base url for angular 2 http requests

but that works for beta version. I'm using RC6 and can't make it to work. Any help would be appreciated.


If you run your json backend on the same server which provides your client code - you don't need to specify port in url. For other url settins (like I have all my services under /api/) I use a separate helper class which deals with all configuration and such and this one has /api/ hardcoded, but it's only in that one place. Easy to change either manually or during build process.

The class can be something like that:

export class Configuration {
    private static _apiUrl = "/api";
    private static _childUrl = `${Configuration._apiUrl}/child`;

    public static apiUrl(url: string): string {
        return `${this._apiUrl}/${url}`;

    public static getChildComponentUrl(url: string): string {
        return `${this._childUrl}/${url}`;