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/... 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..