Set Environment Variables in Angular

cover-photo

Set Environment Variables in Angular



blog-photo

In this post we are going to learn about setting environment variables in angular. So first let us know why it's required. When we are working on a project we might encounter a situation where we might want a piece of functionality to work differently on your local development and your live project, there might be scenarios where we want use to different Databases while working on local development and the Live Database, also we need to use two different urls or sources to fetch the data from. For example our API endpoints.

So basically what most of the people do is keep both the urls and keep the one commented which is not required.

So Angular here provides more simpler way to do this.


blog-photo

Check the folder structure shown above to lead you to the environments folder which resides in src folder of our angular application. Angular creates this folder and two files in it namely environment.prod.ts and environment.ts by default whenever you create an angular application.

So we have to use these 2 files for storing our variables used by application. We will store our local development variables in environment.ts and store all our production site variables in our environment.prod.ts file. These files contains below code initially by default when angular creates it.

// environment.prod.ts 
export const environment = {
  productiontrue, 
};


// environment.ts
export const environment = {
  productiontrue, 
};

So we can append this json object and add the variables we want here in both the files as shown in below snippet.

// environment.prod.ts 
export const environment = {
  productionfalse,
  baseUrl'https://livesite.com/api/',
  domain'livesite.com'  
};


// environment.ts
export const environment = {
  productionfalse,
  baseUrl'http://localhost:8000/api/',
  domain'localhost'  
};


And after that we just have to import the environment file into our components and angular will automatically provide one of the files depending upon the environment. When we use ng serve the variables from the environment.ts file will be imported and when we use ng build --prod the variables from the environment.prod.ts file will be imported.

import { environment } from '../environments/environment';

// use as belows
this.apiUrl = environment.baseUrl;


I hope you have understood the usage of environment variables in Angular.

Happy Coding!