How do I set the baseUrl for Angular HttpClient?
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/
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: "..."};
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); }}