I want to remove my local server prefix from my REST API URLs (example, http://localhost:8080) when building for production (ng build --prod).
I get that i
Putting an API_URL in your environment config is a good idea, but if your API and client app is being served from the same server or domain, you can use relative URLs instead. It is much easier to set up and simplifies your build process.
Here is some code that would live in an API service.
get(path: string, params: HttpParams = new HttpParams()): Observable {
return this.http.get(`/api${path}`, { params })
.pipe(catchError(this.formatErrors));
}
If you are using the environment.API_URL, you can still configure that value to be blank.
This can be helpful if you are serving your app and API from separate localhost servers in a development environment. For example, you might ng serve from localhost:4200 and run your API from a PHP, C#, Java, etc. backend on localhost:43210. You will need the API_URL config for development.
get(path: string, params: HttpParams = new HttpParams()): Observable {
return this.http.get(`${environment.api_url}/api${path}`, { params })
.pipe(catchError(this.formatErrors));
}
As a bonus, here is an example of ApiService that is an injectable object you can use in your app!
https://github.com/gothinkster/angular-realworld-example-app/blob/63f5cd879b5e1519abfb8307727c37ff7b890d92/src/app/core/services/api.service.ts
Pay attention to the base ref in your main HTML page as well.