Pass environment variables to an Angular2 app?
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
I would see two ways to do that:
Leverage a JSON configuration in a file. This file would be loaded before boostrapping the application:
var app = platform(BROWSER_PROVIDERS) .application([BROWSER_APP_PROVIDERS, appProviders]); var http = app.injector.get(Http); http.get('config.json').subscribe((config) => { return app.bootstrap(AppComponent, [ provide('config', { useValue: config }) ]); }).toPromise();
Here is a corresponding plunkr describing the global approach: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.
Leverage a configuration module:
export const CONFIG = { (...) };
that will be imported and included in providers when bootstrapping the application:
import {CONFIG} from './config'; bootstrap(AppComponent, [ provide('config', { useValue: CONFIG }) ]);
With the two approaches, configuration can be defined for each environment when packaging the application.
This question could also give you hints about how to package an Angular2 application:
- How do I actually deploy an Angular 2 + Typescript + systemjs app?