Reputation: 3237
I'm in the early phases of development in my project and constantly switching back and forth between using a local dev backend service vs using the real production version (in my development angular environment that is).
So I'm basically switching back and forth between commenting lines in my code:
service.ts
this.http.post(
'http://127.0.0.1:port/endpoint',
//'https://production-server.com/endpoint',
// ...
I've just upgraded to using my environment.ts
and environment.prod.ts
files properly
environment.ts
export const environment = {
production: false,
backendServiceEndpoint: 'http://127.0.0.1:port/endpoint',
// bunch of other dev config stuff
};
environment.prod.ts
export const environment = {
production: false,
backendServiceEndpoint: 'https://production-server.com/endpoint',
// bunch of other production config stuff
};
So now my code actually looks like:
service.ts
this.http.post(
environment.backendServiceEndpoint
// ...
So for the "bunch of other config stuff" this was a really useful change. But I still want to test the production backend while in dev mode with angular. I know I could use ng serve --prod
to get the environment.prod
config, but I don't want everything to switch out, just the backendServiceEndpoint
. What's the best pattern/method for achieving this?
I was thinking that an ideal way would be to have some custom flag I can tack onto the ng serve
command, but I don't think it's possible for me to make one.
Added context: This is actually an ionic project. So I'm really using ionic serve
Upvotes: 0
Views: 1922
Reputation: 243
I solved this problem by using the Typescript compiler API to transpile environment.ts
in memory. I've documented that here, along with an alternative solution:
https://stackoverflow.com/a/63065866/843625
Upvotes: 1
Reputation: 2367
You would want to use ng serve --configuration=<your env name>
and wire this up in your angular.json
file under "configurations".
See: https://angular.io/guide/build#configure-target-specific-file-replacements
If your configuration is complex and needs to change based on other variables I would use a configuration "service". I dynamically set/change things for instance with my HttpClient
usage and what the user is entitled to.
Duplicate of How to set environment via `ng serve` in Angular 6
Upvotes: 1
Reputation: 6529
You have several options outlined in the angular build docs
My recommended approach will be to use the proxy.conf.json
file to proxy all requests. Which you can alternate by how you call the serve command.
ng serve --proxy-config proxy.conf.json
An example proxy file:
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"logLevel": "debug"
}
}
This will rewrite the api
in the path, but depends on your use case.
Upvotes: 2