1

I've been using spring boot which has a nice feature of using the system environment variables in properties file, now I want to use the system environment variable to set the backend server url in angular. I'm not sure how this works in angular.

For eg. BACKEND_URL=http://somerandomurl

I don't want to hardcode the server url in config file. I want to do something like apiurl=$(BACKEND_URL)

This is due to fact that I'll be using kubernetes while deployment.

1 Answer 1

3

You can use Angular environment.ts file to configure your backend URLs.

In fact you can assign multiple backend url as you wish. For example (prod, dev, qa)

 // environment.ts
    export const environment = {
      production: false,
      baseUrl: 'http://localhost:3333'
    };
    
 // environment.prod.ts
    export const environment = {
      production: true,  
      baseUrl: 'https://jsonplaceholder.typicode.com'
    };

 // environment.qa.ts
    export const environment = {
      production: true,  
      baseUrl: 'https://jsonplaceholder.typicode.com'
    };

Then you can build the angular project with relevent environment you prefer. Angular will assign the base urls acccording to the passed parameter in build time.

ng build --configuration=prod
ng build --configuration=qa

From herewith Im attaching reference link of official angular documentation on how to do it here.

Also please find the practical demonstration here. Please refer to the stackblitz example here and it relevent article here.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I don't know the url before deploying the application? Like I don't want to hardcode the url into the config file
Then u need to get the url from an api and set it in your store or localStorage and use it all across your application @VivekGupta
This doesn't seem to be an answer to the OP, since you DO need to hardcode the values into the environment file (one or the other), but I suppose this solution is what's possible in Angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.