3

Is there any way to access environment variable in angular 2 components when using ng serve?

E.g.:

API_URL=http://api.test.com ng serve

How can I access API_URL in Angular components?

Thanks in advance!

wexpixies
  • 75
  • 5

1 Answers1

2

The CLI provides "environment" files just for that purpose. For development, put your configuration in the file:

src\environments.ts

For production, use the"

src\environments.prod.ts

When you build the application with:

ng build -prod 

(or just ng build since -prod is the default)

Angular will use the environment.prod.ts file in place of the environment.ts file.

Ben Richards
  • 3,437
  • 1
  • 14
  • 18
  • Thanks for reply Boyan! When I use environments.ts files, I should know values of environment variables beforehand to describe each of them for each environment, but the main purpose is that API_URL can be dynamically changed and how I can access it directly in components without adding new values for environments – wexpixies Feb 10 '17 at 16:54
  • What you are asking for can be done, but it gets more complex fast. Check out my other answer about providing configuration at run-time. http://stackoverflow.com/questions/42077544/angular-2-and-team-city-production-environment-variables-best-practices/42078017#42078017 – Ben Richards Feb 10 '17 at 16:56