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