Pass environment variables to an Angular2 app?

Zlatko picture Zlatko · Apr 10, 2016 · Viewed 33.1k times · Source

I need to pass the backend url to my Angular2 app, since production and dev servers are hosted on different locations.

I know I could store such things in an external config.json and load upon startup. This, however, seems like unnecessary extra call to server before the app can get started.

Alternatively, what I do now is I do create a single global variable, which I inject in gulp depending on build. My app isn't a lib that needs to be reusable I don't believe I should hit unexpected global name clashes. But it's not a good practice.

I wonder if there's a third, better solution?

Answer

Boris Siscanu picture Boris Siscanu · Oct 18, 2016

Just put variables inside the environment object.

export const environment = {
  production: false,
  url: 'http://localhost:3000/api'
};

After that, you could import and use it. Angular Cli will swap files automatically.

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

P.S. Variables are available in environment object.

this.url = environment.url