1

I am currently creating an angular application that uses a REST API to send and receive calls from an instance at the backend. Currently, this URL is defined as an environment variable as below:

export const environment = {
  production: false,
  loggerLevel: NgxLoggerLevel.DEBUG,
  disableConsoleLogging: false,
  lang: 'en',
  api: {
    . //other variables
    .
    .
    host: "http://mycoolurl.com/rest/v11_1/",
    . 
    . //more variables
    .
  }
};

Now, there is a similar question that addresses this issue here but even that uses a specific settings.json file that would be fetched using APP INITIALIZER. Another similar question here also suggested me to use a separate JSON file.

A recent requirement change stated that the user should be able to specify the URL that he wants to send the REST calls to, so preferably it would be an input field that he would be entering the URL into and it would update the host in the environment file. How do I achieve this?

Unfortunately, I cannot change the entire implementation and remove the host from the environment, it is being imported and used in so many places throughout the application.

Muhammad Hamza
  • 823
  • 1
  • 17
  • 42

1 Answers1

1

You can't really change the value of the environment directly in the code because it is bundled with everything else. It is also a really bad approach because you would overwrite the value everytime you update the application. Store it separately server-side!

Option A:

Use the APP_INITIALIZER and overwrite the value of the environment there, after loading it: environment.api.host = loadedValue

That will only work properly if you don't use the value before that. It would only be used before that if you use it in module definitions / configuration and classes that you inject into the initializer. So that might work for you.

Option B

This is rather ugly but would work fine:

Save the api url in a separate javascript file that looks somewhat like this:

window.userEnvironment = { host: "http://custom-host" };

Load this javascript in the <head> part of the index.html with: <script src="user-env.js"></script>. That way it is loaded before angular is loaded. This is ensured by the browser!

Now inside the environment.ts file you can do this:

export const environment = {
  ...
};

const userEnv = (window as any).userEnvironment;
if (userEnv) Object.assign(environment, userEnv);

This overwrites the environemt value with the values from the user-env.js file.

You dont have to do that in the environment. You could also do it somewhere else. You just have to be sure to do it before environment is used. Also, if you have multiple environment you would need to it in all environment files.

x4rf41
  • 5,184
  • 2
  • 22
  • 33