user3805731
user3805731

Reputation: 295

Angular 2 / 4 change env variable after build

I read that you can put your environement variable in environement.ts / environement.prod.ts . ok

But this file are compile so I can't change it after the build. Is the anyway to do that ?

(I am using angular-cli)

Thanks

Upvotes: 6

Views: 21210

Answers (4)

asad nobi
asad nobi

Reputation: 1

(function (window) {
 window['env'] = window['env'] || {};
 // Environment variables
 window['env']['apiUrl'] = 'your-api-url';
})(this);

Upvotes: 0

scott_dennis
scott_dennis

Reputation: 77

After the build, we can find main.bundle script file, you will find and change the environment variables.

in main.bundle.js file :

var environment = {
  production: false,
  serviceUrl: "<<URl>>",
  prodService: "environment"
};

Upvotes: 4

Kapil Thakkar
Kapil Thakkar

Reputation: 870

We can find all environment variable in var environment = {} object in main.bundle.js file.

NOTE: Restart server after changes.

Upvotes: 7

user4676340
user4676340

Reputation:

Yup, just like this :

environment.ts

export const environment = {
    env: 'Dev'
};

environment.prod.ts

export const environment = {
    env: 'Prod'
};

EDIT What I did to solve that issue is using the window object like so :

export const environment = {
    env: window['env'] || 'Dev' // you get it for prod
};

And in the index.html added this :

<script src="./config.js"></script>

And in the config.js file, the "system guy" can put this :

window['env'] = 'New environment';

This way, if no config file is provided, the env variable will have a value, and if the config file is provided, it will take the value from it.

Upvotes: 8

Related Questions