Angular CLI: Environment Variables

Image for post
Image for post

It’s common to find yourself needing different values for different environments when working on a large angular 2 application. For example, you may need to use a mock server for your web service endpoints when developing and do the integration with the real endpoints at a later stage.

I thought I’d share what I’ve learnt about how the CLI tool can help in achieving such objectives.

environment.ts

The first step is creating an environment file that corresponds with the new environment name. For example if you’re calling the new environment test, then your filename will be environment.test.ts. This file will go under src/app/environments.

angular-cli.json

The next step is to add new entry under “environments” in the angular-cli.json. For example, if you want to call the new environment “test” your JSON would look like the following:

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

using your environment.ts

Anytime you want to reference a value in your environment file, you simply import the base environment class (environment.ts) and Angular CLI will swap it for you at build time. i.e. if you have an http service that uses different URLs based on the environment, you do the following:

// src/environments/environment.ts
export const environment = {
production: false,
url: 'http://localhost:3000/getResults'
};

and the way you reference it inside the service:

// src/app/test.service.ts
import { environment } from '../environments/environment';

@Injectable()
export class TestService {
url: environment.url
}

serving/building your app

Angular CLI will replace the values in your environment.ts based on which flag you provide it at serve or build time. In order to tell it which environment you want to load, for our example it can be done as so:

ng serve --environment=test
or
ng build --environment=test

That’s it. I hope this was useful. Thank you for taking the time.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store