Application Configuration

where should i store it ?

i am previous post (Load configuration from external file) i’ve described the way to load the configuration from a json file.

Here, i want to address the option to have our configuration as part of our application, in a class.

We could use angular-cli’s environment.ts file, and add values to the constant that is declared there. but i want to show a more elegant way. this is based on the angular DI documentation and on a stackoverflow answer.

1) app.config.ts

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("app.config");

export interface IAppConfig {
    apiEndpoint: string;
}

export const AppConfig: IAppConfig = {    
    apiEndpoint: "http://localhost:15422/api/"    
};

2) app.module.ts

import { APP_CONFIG, AppConfig } from './app.config';

@NgModule({
    providers: [
        { provide: APP_CONFIG, useValue: AppConfig }
    ]
})

3) your.service.ts

import { APP_CONFIG, IAppConfig } from './app.config';

@Injectable()
export class YourService {

    constructor(@Inject(APP_CONFIG) private config: IAppConfig) {
             // You can use config.apiEndpoint now
    }   
}

Now you can inject the config everywhere without using the string names and with the use of your interface for static checks.

please note: in my tests, i get warnings if i use the : IappConfig statement in the constractor of “YourService”. you can omit this, and things continue to work as expected (eventually, javascript doesn’t have interfaces)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s