Configure environments in Angular

Configure environments in Angular

In this post, I am going to discuss about configuring environment settings in a angular application using angular-cli. The solution was tested only in version 7.

Create a new angular project using the following command. ng new env-demo

Let us assume that we are having three different databases for dev, uat and production. Locate the environments folder. You will see two files
a) environment.ts – settings for the development environment.
b) environment.prod.ts – settings for the production environment.

Add one more file environment.uat.ts in the environments folder. The filename suffix uat and the environment name should match. Our new environment is uat.

Add a setting named dbUrl in all the environments and have a different values for each environment.

The environment settings are configured in the angular.json file. There is a section called configurations which currently has one value for production. It looks like the

Create one more section in the configurations section called uat which looks like following.

To test the settings, let us use the settings in the app component. Import the environment module in the app component. You have to refer only the environment.ts file.
import { environment } from '../environments/environment';
The angular compiler will do the transformation for you.

The complete code snippet for the angular.component.ts file is pasted below

When you run the command ng build -c uat the angular compiler will correctly transfer the settings in the uat environment to the environment.ts file.

There is one more thing that we need to do if we want to test this using the ng serve command. Locate the section serve in the angular.json file and add the section uat in the configurations section which is nested under serve section.

Now when you run the command ng serve -c uat the correct value of the dbUrl settings will be available in the app component.

Leave a Reply

Your email address will not be published. Required fields are marked *