In Angular, you can set a default base URL for all API calls using an HTTP Interceptor.
Method : Using HTTP Interceptor (Recommended)
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {
private baseUrl = 'https://api.example.com/';
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({
url: this.baseUrl + req.url
});
return next.handle(modifiedReq);
}
}
Register Interceptor in app.module.ts:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { BaseUrlInterceptor } from './base-url.interceptor';
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: BaseUrlInterceptor, multi: true }
]