Change Environment at Runtime in Angular with Heroku

Abhishek Garg
3 min readAug 9, 2018

--

Hi All, Today we will talk about that how we can change our Angular app environment at run time when deploying the code on Heroku Server.

If you need help deploy angular webapp on heroku you can refer to blog at https://www.infoxen.com/blog/how-to-deploy-angular-6-app-on-heroku/

So, first we discuss that why we need this environment at run time. The situation is as described:

As normally every app is deployed in multiple environments e.g. staging, prod and service URL will be different for every environment. The solution for this is to have multiple environment file and choose one of them at the time of deployment dynamically.

Let’s take an example , you have this type of environemnt file:

This is your environment.prod.ts file and your have another api_url . So, will make another environment file as below:

We have named this file environment.test.ts and changed the api_url to http://www.yahoo.com . So, now you have three environment file. One is for your local, one is prod and another is test.

Now, the next step is how would you choose your environment file at run time. The steps for this is given below:

  1. Open the file angular.cli.json . You will find your file like this:
"apps": [{
...
"scripts": [],"environmentSource": "environments/environment.ts","environments": {"dev": "environments/environment.ts","prod": "environments/environment.prod.ts"}
}
]

We will add our new environment.test.ts file inenvironments section and then this section will we like:

"environments": {"dev": "environments/environment.ts","prod": "environments/environment.prod.ts","test": "environments/environment.test.ts"}

2. So, first step is complete. Now, this is the time to move on next step and for that open your package.json file. You will find your file like this:

In the image you can see the postinstall section and replace this as below:

"postinstall": "ng build --aot --prod --env=${environment}"

3. Our application code is now complete. The next step is to create environment variable at Heroku. Open Your app on heroku go to settings.

Then choose Reveal Config Vars . You can see the image:

In the end of the image, you can find KEY and VALUE section. We will put our environment var here as:

And then click on Add button to add the variable. Now the variable is added.

The process is complete. When you will deploy your app the postinstall command will run and will find the environment variable on heroku. Then your app will be deployed with environment.test.ts file.

So, guys that’s all for now. Thanks for reading the article. If you have any queries about it then you can post your comment.

About me: I work at “Infoxen Technologies” as angular developer :)

--

--