63

I did not find a way in the documentation to set the base API URL for HTTP requests. Is it possible to do this with the Angular HttpClient?

Boann
  • 44,932
  • 13
  • 106
  • 138
Stepan Suvorov
  • 21,636
  • 25
  • 93
  • 166
  • 2
    You could create an [interceptor](https://angular.io/api/common/http/HttpInterceptor) that will update the url with whatever base you want. – Adrian Fâciu Aug 17 '17 at 13:00
  • isn't it an overhead to use interceptors for this case? – Stepan Suvorov Aug 17 '17 at 13:01
  • If you want to change only this yes it might be. Another option would be to have a simple function getApiUrl() that will make any transformations required, like adding the base path. – Adrian Fâciu Aug 17 '17 at 13:04
  • Or create a class derived from [XHRBackend](https://angular.io/api/http/XHRBackend) and create the connection with the base url in place. There are pros and cons for each approach, I'm not aware of any 'simpler' way of providing this. – Adrian Fâciu Aug 17 '17 at 13:06
  • I personally use an interceptor but recommend to add other functionalities to it as well such as setting headers for all requests. – Daniel Cuesta Jan 02 '18 at 18:04

6 Answers6

93

Use the new HttpClient Interceptor.

Create a proper injectable that implements HttpInterceptor:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class APIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const apiReq = req.clone({ url: `your-api-url/${req.url}` });
    return next.handle(apiReq);
  }
}

The HttpInterceptor can clone the request and change it as you wish, in this case I defined a default path for all of the http requests.

Provide the HttpClientModule with the following configurations:

providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: APIInterceptor,
      multi: true,
    }
  ]

Now all your requests will start with your-api-url/

sparty02
  • 484
  • 1
  • 4
  • 12
TheUnreal
  • 18,980
  • 36
  • 129
  • 231
  • 7
    This is great! One thing though, you do not need to use Injectable decorator here, it is only required when you want ot inject something into decorated class. – BroiSatse Jan 07 '18 at 01:30
  • 3
    And if you want different HttpClients to use different base urls how do you manage that? Some sort of marker in the request that the injectable switches on, multiple injectors. Doesn't seem at all elegant to me. – Neutrino Sep 05 '18 at 16:33
  • 14
    I cry when I see this code. Why cant we just create a client instance that has a `baseUrl` property instead of this middleware-like solution that is over the top for such a simple use case – Flame Oct 12 '18 at 14:25
  • 2
    Am I the only one to see an overhead on `req.clone` by doing it for each request? HttpRequest seems to be immutable, so on big request, I guess there would add a significant overhead processing? I understand it looks neat, but isn't it adding a useless reprocessing? Am I missing something? FYI: I am a front noob – Aurelien May 29 '20 at 13:33
41

Based on TheUnreal's very useful answer, the interceptor can be written to get the base url through DI:

@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {

    constructor(
        @Inject('BASE_API_URL') private baseUrl: string) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const apiReq = request.clone({ url: `${this.baseUrl}/${request.url}` });
        return next.handle(apiReq);
    }
}

BASE_API_URL can be provided by the application module:

providers: [
    { provide: "BASE_API_URL", useValue: environment.apiUrl }
]

where environment is the object automatically created by the CLI when generating the project:

export const environment = {
  production: false,
  apiUrl: "..."
}; 
Alexei - check Codidact
  • 17,850
  • 12
  • 118
  • 126
7

Why not create an HttpClient subclass that has a configurable baseUrl? That way if your application needs to communicate with multiple services you can either use a different subclass for each, or create multiple instances of a single subclass each with a different configuration.

@Injectable()
export class ApiHttpClient extends HttpClient {
  public baseUrl: string;

  public constructor(handler: HttpHandler) {
    super(handler);

    // Get base url from wherever you like, or provision ApiHttpClient in your AppComponent or some other high level
    // component and set the baseUrl there.
    this.baseUrl = '/api/';
  }

  public get(url: string, options?: Object): Observable<any> {
    url = this.baseUrl + url;
    return super.get(url, options);
  }
}
Neutrino
  • 6,048
  • 4
  • 37
  • 64
5

you don't necessarily need a base URL with HttpClient, the docs says you just have to specify the api part of the request, if you are making calls to the same server it is straightforward like this:

this.http.get('/api/items').subscribe(data => {...

However, you can if you need or want to, specify a base URL.

I have 2 suggestions for doing that:

1. A helper class with a static class property.

export class HttpClientHelper {

    static baseURL: string = 'http://localhost:8080/myApp';
}


this.http.get(`${HttpClientHelper.baseURL}/api/items`); //in your service class

2. A base class with a class property so any new service should extend it:

export class BackendBaseService {

  baseURL: string = 'http://localhost:8080/myApp';

  constructor(){}
}

@Injectable()
export class ItemsService extends BackendBaseService {

  constructor(private http: HttpClient){  
    super();
  }
      
  public listAll(): Observable<any>{    
    return this.http.get(`${this.baseURL}/api/items`);
  }

}
ssuperczynski
  • 2,473
  • 2
  • 37
  • 57
skinny_jones
  • 454
  • 1
  • 5
  • 12
5

Excerpts from Visual studio 2017 asp.net core webapi angular sample application.

include below lines in Main.ts

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

in your component

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }

my complete main.ts code looks like below

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

my component code looks like below

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'fetch-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.scss']
})

export class WeatherComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}

interface WeatherForecast {
  dateFormatted: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

Moorthi Daniel
  • 149
  • 2
  • 5
  • This is a pretty great solution. Especially because it can use the --base-href functionality that angular already inlcudes - makes it so easy to host api + angular app in a subfolder. – Terrance00 Mar 14 '19 at 12:44
2

I think there is no default way to do this. Do the HttpService and inside you can define property of your default URL, and make methods to call http.get and others with your property URL. Then inject HttpService instead of HttpClient

Anton Lee
  • 664
  • 4
  • 10