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?
-
2You 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
-
1isn'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
7 Answers
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/
-
8This 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
-
6And 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
-
48I 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
-
4Am 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
-
The problem with this is that it will change ALL requests, not just the one done to the api. For example there is something like `angular-svg-icon` that uses the HttpClient and does not work anymore. – Mick Oct 20 '21 at 15:52
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: HTTP_INTERCEPTORS,
useClass: BaseUrlInterceptor,
multi: true
},
{
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: "..."
};

- 3,190
- 3
- 44
- 61

- 22,016
- 16
- 145
- 164
-
1
-
1@emaillenin - since there is more than just one comment, I have added the information within the answer. Basically, the value is provided "globally". – Alexei - check Codidact Aug 27 '18 at 08:11
-
@Alexei what if we need consume 2 different BASE_API_URL? I mean we have a project and it uses 2 API servers with different base – user1325696 Dec 21 '18 at 06:06
-
@user1325696 - you can define two properties in `environment` object and provide two values in application module (I assume that different components use either of them so it makes sense to inject whatever is needed in that particular component). – Alexei - check Codidact Dec 21 '18 at 06:14
-
@Alexei the problem is that how that interceptor would be able to define which baseUrl is to use. – user1325696 Dec 21 '18 at 22:19
-
1and how you call that environment and other setup docs here: https://angular.io/guide/build – user606669 Jun 12 '20 at 17:09
-
thats what my hero alexei is! thanks for it..exactly what I was looking for – minigeek Apr 01 '21 at 10:09
-
2@Alexei-checkCodidact You don't need to inject `BASE_API_URL` you can simply access it using `environment.apiUrl`, this value will change based on your current environment.. – Offir Jun 28 '22 at 10:20
-
@Alexei-checkCodidact What is the best way to exclude requests to external api to avoid a `https://api.external/localhost:44334` ? – Offir Jun 30 '22 at 08:46
Everybody who followed Alexei answer and couldn't make it work like me - it's because you also have to add to providers array this element
{
provide: HTTP_INTERCEPTORS,
useClass: BaseUrlInterceptor,
multi: true
}
Unfortunately I have too low reputation to add a comment to his answer.

- 414
- 4
- 8
-
6
-
6@BraianSilva thanks buddy, you actually are the reason I can comment now! – Hakej Jul 10 '21 at 07:58
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);
}
}

- 8,496
- 4
- 57
- 83
-
1and anyone else who is thinking of doing this please don't. HttpClient is a "Final" class and Angular does not recommend extending "Final" classes as its internal implementation might change. More on this here: https://github.com/angular/angular/blob/13.1.1/docs/PUBLIC_API.md#final-classes – Niragh Dec 30 '21 at 09:17
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;
}

- 157
- 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
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`);
}
}

- 3,190
- 3
- 44
- 61

- 470
- 1
- 5
- 12
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

- 684
- 4
- 10
-
I did it for Http service, but hoped that HttpClient is a bit smarter – Stepan Suvorov Aug 17 '17 at 12:58