I am currently developing an application for Angular 2 based on angular2-seed. I am looking what the best way is to store enviroment variables so I can store different values for, for example, a API url.
The default config file (seed.config.ts) already has 2 environments that are used when building for production or development:
/**
* The enumeration of available environments.
* @type {Environments}
*/
export const ENVIRONMENTS: Environments = {
DEVELOPMENT: 'dev',
PRODUCTION: 'prod',
STAGING: 'staging'
};
Further in this config file, a class SeedConfig is defined that has some constants defined, I guess this would be the place where I should add my variables as wel. That gives me:
export class SeedConfig {
PORT = argv['port'] || 8000;
URL_DEV = 'www.example.com';
URL_PROD = 'www.example.com';
Now what would be the best approach to access these variables in my template, based on the configured environment?
1)
Provide the class
bootstrap(AppComponent, [provide('SeedConfig', {useClass: SeedConfig}]);
or
@Component({
selector: 'app-component',
providers: [provide('SeedConfig', {useClass: SeedConfig}],
...
})
access it like
@Component({
selector: 'some-component',
template: `<div>{{seedConfig.DEVELOPMENT}}</div>
...
})
export class SomeComponent {
constructor(@Inject('SeedConfig') private seedConfig:any) {}
}
2)
or alternatively to get proper autocompletion
Provide the class
bootstrap(AppComponent, [SeedConfig]);
or
@Component({
selector: 'app-component',
providers: [SeedConfig],
...
})
access it like
@Component({
selector: 'some-component',
template: `<div>{{seedConfig.DEVELOPMENT}}</div>
...
})
export class SomeComponent {
constructor(private seedConfig:SeedConfig) {}
}
The 2nd approach has the advantage that autocompletion can list all configured properties but it also requires SeedConfig to be imported everywhere, where it is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With