Setting Up Environment Variables In Angular 5
Posted By : Satendra Shakya | 27-May-2018
Hi folks! Today I'm gonna show you how to set environment variables from different environment mode for the angular5 application. I'm dividing this tutorial into few steps given below...
1. creating env file for different environment mode.
2. Setting env file for the corresponding mode in Angular CLI.
3. setting startup command for Application.
4. using env variables in components and services.
Here I'm assuming you have already created your angular application using CLI. So let's get started from the step 1.
1. Creating env file for different environment mode
Just goto "/src/environments/", you will find a file "environment.ts" file, copy contents of that file and create the new file for different environment mode.
so here I have created two more files, one for staging and one for production.we will use the preexisting file i.e. environment.ts for development mode. you can set all environment variables in all these three files for different environments.
2. Setting env file for the corresponding mode in Angular CLI
Now we have to set these file for different environment mode. so open .angular-cli.json file. find the key "environments" and replace the key content from the following content.
Now our environment variables are ready to use. let's move to next step.
3. Setting startup command for Application
Now set the argument given in below command according to environment mode.
4. using env variables in components and services
just add the line `import { environment } from '../environments/environment';` in you components or services and you can access all the variables using "environment.variablesName".
Note: "../environments/environment" path will be changed for child directory in src/app/...
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Satendra Shakya
An experienced mean stack developer having work experience in nodeJs, Angular and MongoDB. Apart from these he likes to play chess and solving riddles like Rubik cubes.