Skip to content

Instantly share code, notes, and snippets.

  • Select an option

  • Save AndreasGassmann/07c89d4eece822eabb153d48d5045f39 to your computer and use it in GitHub Desktop.

Select an option

Save AndreasGassmann/07c89d4eece822eabb153d48d5045f39 to your computer and use it in GitHub Desktop.

Revisions

  1. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 8 additions and 0 deletions.
    Original file line number Diff line number Diff line change
    @@ -19,10 +19,15 @@ Open your existing module and add the following two lines to your list of provid
    ```typescript
    import { APP_INITIALIZER } from '@angular/core';
    import { AppConfig } from './app.config';
    import { HttpModule } from '@angular/http';

    ...

    @NgModule({
    imports: [
    ...
    HttpModule
    ],
    ...
    providers: [
    ...
    @@ -34,8 +39,11 @@ import { AppConfig } from './app.config';
    ```

    The first line makes AppConfig class available to Angular2.

    The second line uses APP_INITIALIZER to execute Config.load() method before application startup. The 'multi: true' is being used because an application can have more than one line of APP_INITIALIZER.

    Make sure you set "HttpModule" in "imports" section if you want to make http calls using Angular2 built in Http library.

    ### In app.config.ts

    Create a class AppConfig and name the file 'app.config.ts' (you can use a name of your choice).
  2. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 45 additions and 29 deletions.
    Original file line number Diff line number Diff line change
    @@ -4,13 +4,13 @@ In this demonstration I will show you how to read data in Angular2 final release

    This is how the demonstration will load data:

    a) It will read an 'env.json' file. This file indicates what is the current working environment. Options are: 'production' and 'development';
    a) It will read an env file named 'env.json'. This file indicates what is the current working environment. Options are: 'production' and 'development';

    b) It will read a second JSON file. If env is production, the file is 'config.production.json'. If env is development, the file is 'config.development.json'.
    b) It will read a config JSON file based on what is found in env file. If env is "production", the file is 'config.production.json'. If env is "development", the file is 'config.development.json'.

    All these reads will be done before Angular2 starts up the application.

    It assumes you have a working application, with a module already configured.
    It assumes you already have a working application, with a module and everything set up.

    ### In Your Module

    @@ -34,13 +34,13 @@ import { AppConfig } from './app.config';
    ```

    The first line makes AppConfig class available to Angular2.
    The second line uses APP_INITIALIZER to execute Config.load() method before application startup. The 'multi: true' is being used because your can have more than one line of APP_INITIALIZER.
    The second line uses APP_INITIALIZER to execute Config.load() method before application startup. The 'multi: true' is being used because an application can have more than one line of APP_INITIALIZER.

    ### In app.config.ts

    Create a class and name it 'app.config.ts' (you can use a name of your choice if you want).
    Create a class AppConfig and name the file 'app.config.ts' (you can use a name of your choice).

    This is the place we will do the reading of env and configuration files. The variables of configuration files will be stored in the class so we can get them later.
    This is the place we will do the reading of env and config files. The data of both files will be stored in the class so we can retrieve it later.

    Note that native Angular Http library is used to read the json files.

    @@ -59,22 +59,32 @@ export class AppConfig {

    }

    public get(key: any) {
    /**
    * Use to get the data found in the second file (config file)
    */
    public getConfig(key: any) {
    return this.config[key];
    }

    /**
    * Use to get the data found in the first file (env file)
    */
    public getEnv(key: any) {
    return this.env[key];
    }

    /**
    * This method:
    * a) Loads "env.json" to get what is the current environment (e.g.: 'production', 'development')
    * a) Loads "env.json" to get the current working environment (e.g.: 'production', 'development')
    * b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
    */
    public load() {
    return new Promise((resolve, reject) => {
    this.http.get('env.json').map( res => res.json() ).subscribe( (envResponse) => {
    this.http.get('env.json').map( res => res.json() ).catch((error: any):any => {
    console.log('Configuration file "env.json" could not be read');
    resolve(true);
    return Observable.throw(error.json().error || 'Server error');
    }).subscribe( (envResponse) => {
    this.env = envResponse;
    let request:any = null;

    @@ -93,17 +103,22 @@ export class AppConfig {
    } break;
    }

    request
    .map( res => res.json() )
    .catch((error: any) => {
    console.error('Error reading ' + envResponse.env + ' configuration file');
    resolve(error);
    return Observable.throw(error.json().error || 'Server error');
    })
    .subscribe((responseData) => {
    this.config = responseData;
    resolve(true);
    });
    if (request) {
    request
    .map( res => res.json() )
    .catch((error: any) => {
    console.error('Error reading ' + envResponse.env + ' configuration file');
    resolve(error);
    return Observable.throw(error.json().error || 'Server error');
    })
    .subscribe((responseData) => {
    this.config = responseData;
    resolve(true);
    });
    } else {
    console.error('Env config file "env.json" is not valid');
    resolve(true);
    }
    });

    });
    @@ -114,52 +129,53 @@ export class AppConfig {
    See that we used resolve() in all scenarios because we don't want the application to crash if any problem is found in the configuration files. If you prefer, you can set error scenarios to reject().

    ### In env.json
    This is the place you will configure the current development environment. You may add this file to .gitignore to your convenience.
    This is the place you will configure the current development environment. Allowed values are 'development' and 'production'.

    ```json
    {
    "env": "development"
    }
    ```
    You may add this file to .gitignore to your convenience.

    ### In config.development.json
    This is the place you will configure development environment variables. You may add this file to .gitignore to your convenience.

    You can add as many variables you want in this JSON file.
    This is the place you will configure development config variables. You can add as many variables you want in this JSON file.

    ```json
    {
    "host": "localhost"
    }
    ```
    You may add this file to .gitignore to your convenience.

    ### In config.production.json
    This is the place you will configure production environment variables. You may add this file to .gitignore to your convenience.

    You can add as many variables you want in this JSON file.
    This is the place you will write production config variables. You can add as many variables you want in this JSON file.

    ```json
    {
    "host": "112.164.12.21"
    }
    ```
    You may add this file to .gitignore to your convenience.

    ### In Any Angular2 class
    This is how we read a configuration variable. In this case, we are reading the 'host' variable and the current env.
    Example of how we read the values previously loaded from both files. In this case, we are reading the 'host' variable from config file and 'env' from the env file.

    ```typescript
    import { AppConfig } from './app.config';

    export class AnyClass {
    constructor(private config: AppConfig) {

    // note that AppConfig is injected into a private property of AnyClass
    }

    myMethodToGetHost() {
    // will print 'localhost'
    let host:string = config.get('host');
    }

    myMethodToGetCurrentEnv() {
    // will print 'development'
    let env: string = config.getEnv('env');
    }
    }
  3. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 14 additions and 7 deletions.
    Original file line number Diff line number Diff line change
    @@ -63,8 +63,8 @@ export class AppConfig {
    return this.config[key];
    }

    public getEnv() {
    return this.env;
    public getEnv(key: any) {
    return this.env[key];
    }

    /**
    @@ -88,15 +88,16 @@ export class AppConfig {
    } break;

    case 'default': {
    alert('Database adapter not defined');
    console.error('Environment file is not set or invalid');
    resolve(true);
    } break;
    }

    request
    .map( res => res.json() )
    .catch((error: any) => {
    console.error(error);
    reject(error);
    console.error('Error reading ' + envResponse.env + ' configuration file');
    resolve(error);
    return Observable.throw(error.json().error || 'Server error');
    })
    .subscribe((responseData) => {
    @@ -110,6 +111,8 @@ export class AppConfig {
    }
    ```

    See that we used resolve() in all scenarios because we don't want the application to crash if any problem is found in the configuration files. If you prefer, you can set error scenarios to reject().

    ### In env.json
    This is the place you will configure the current development environment. You may add this file to .gitignore to your convenience.

    @@ -142,7 +145,7 @@ You can add as many variables you want in this JSON file.
    ```

    ### In Any Angular2 class
    This is how we read a configuration variable. In this case, we are reading the 'host' variable.
    This is how we read a configuration variable. In this case, we are reading the 'host' variable and the current env.

    ```typescript
    import { AppConfig } from './app.config';
    @@ -152,8 +155,12 @@ export class AnyClass {

    }

    myMethod() {
    myMethodToGetHost() {
    let host:string = config.get('host');
    }

    myMethodToGetCurrentEnv() {
    let env: string = config.getEnv('env');
    }
    }
    ```
  4. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 5 additions and 3 deletions.
    Original file line number Diff line number Diff line change
    @@ -6,15 +6,15 @@ This is how the demonstration will load data:

    a) It will read an 'env.json' file. This file indicates what is the current working environment. Options are: 'production' and 'development';

    b) It will read a second file. If env is production, the file is 'config.production.json'. If env is development, the file is 'config.development.json'.
    b) It will read a second JSON file. If env is production, the file is 'config.production.json'. If env is development, the file is 'config.development.json'.

    All these reads will be done before Angular2 starts up the application.

    It assumes you have a working application, with a module already configured.

    ### In Your Module

    Add the following two lines to your list of providers.
    Open your existing module and add the following two lines to your list of providers.

    ```typescript
    import { APP_INITIALIZER } from '@angular/core';
    @@ -38,7 +38,9 @@ The second line uses APP_INITIALIZER to execute Config.load() method before appl

    ### In app.config.ts

    This is the place we do the reading of env and configuration files. The variables of configuration files will stored in the class.
    Create a class and name it 'app.config.ts' (you can use a name of your choice if you want).

    This is the place we will do the reading of env and configuration files. The variables of configuration files will be stored in the class so we can get them later.

    Note that native Angular Http library is used to read the json files.

  5. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 52 additions and 18 deletions.
    Original file line number Diff line number Diff line change
    @@ -1,20 +1,46 @@
    ## In Your Module
    # Reading data before application startup in Angular 2

    In this demonstration I will show you how to read data in Angular2 final release before application startup. You can use it to read configuration files like you do in other languages like Java, Python, Ruby, Php.

    This is how the demonstration will load data:

    a) It will read an 'env.json' file. This file indicates what is the current working environment. Options are: 'production' and 'development';

    b) It will read a second file. If env is production, the file is 'config.production.json'. If env is development, the file is 'config.development.json'.

    All these reads will be done before Angular2 starts up the application.

    It assumes you have a working application, with a module already configured.

    ### In Your Module

    Add the following two lines to your list of providers.

    ```typescript
    import { APP_INITIALIZER } from '@angular/core';
    import { AppConfig } from './app.config';

    ...

    @NgModule({
    ...
    providers: [
    ...
    AppConfig,
    { provide: APP_INITIALIZER, useFactory: (config: AppConfig) => () => config.load(), deps: [AppConfig], multi: true }
    ],
    ...
    });
    ```

    ## In app.config.ts
    The first line makes AppConfig class available to Angular2.
    The second line uses APP_INITIALIZER to execute Config.load() method before application startup. The 'multi: true' is being used because your can have more than one line of APP_INITIALIZER.

    ### In app.config.ts

    This is the place we do the reading of env and configuration files. The variables of configuration files will stored in the class.

    Note that native Angular Http library is used to read the json files.

    ```typescript
    import { Inject, Injectable } from '@angular/core';
    @@ -24,19 +50,19 @@ import { Observable } from 'rxjs/Rx';
    @Injectable()
    export class AppConfig {

    public static config: Object = null;
    public static env: Object = null;
    private config: Object = null;
    private env: Object = null;

    constructor(private http: Http) {

    }

    public static get(key: any) {
    return AppConfig.config[key];
    public get(key: any) {
    return this.config[key];
    }

    public static getEnv(key: any) {
    return AppConfig.env[key];
    public getEnv() {
    return this.env;
    }

    /**
    @@ -46,12 +72,8 @@ export class AppConfig {
    */
    public load() {
    return new Promise((resolve, reject) => {
    if (AppConfig.config != null || AppConfig.env != null) {
    return resolve(true);
    }

    this.http.get('env.json').map( res => res.json() ).subscribe( (envResponse) => {
    AppConfig.env = envResponse;
    this.env = envResponse;
    let request:any = null;

    switch (envResponse.env) {
    @@ -76,7 +98,7 @@ export class AppConfig {
    return Observable.throw(error.json().error || 'Server error');
    })
    .subscribe((responseData) => {
    AppConfig.config = responseData;
    this.config = responseData;
    resolve(true);
    });
    });
    @@ -86,28 +108,40 @@ export class AppConfig {
    }
    ```

    ## In env.json
    ### In env.json
    This is the place you will configure the current development environment. You may add this file to .gitignore to your convenience.

    ```json
    {
    "env": "development"
    }
    ```

    ## In config.development.json
    ### In config.development.json
    This is the place you will configure development environment variables. You may add this file to .gitignore to your convenience.

    You can add as many variables you want in this JSON file.

    ```json
    {
    "host": "localhost"
    }
    ```

    ## In config.production.json
    ### In config.production.json
    This is the place you will configure production environment variables. You may add this file to .gitignore to your convenience.

    You can add as many variables you want in this JSON file.

    ```json
    {
    "host": "112.164.12.21"
    }
    ```

    ## In Any Angular2 class
    ### In Any Angular2 class
    This is how we read a configuration variable. In this case, we are reading the 'host' variable.

    ```typescript
    import { AppConfig } from './app.config';

  6. @fernandohu fernandohu revised this gist Nov 2, 2016. No changes.
  7. @fernandohu fernandohu renamed this gist Nov 2, 2016. 1 changed file with 0 additions and 0 deletions.
  8. @fernandohu fernandohu revised this gist Nov 2, 2016. 1 changed file with 12 additions and 0 deletions.
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    ## In Your Module

    ```typescript
    import { APP_INITIALIZER } from '@angular/core';
    import { AppConfig } from './app.config';

    @@ -11,9 +12,11 @@ import { AppConfig } from './app.config';
    ],
    ...
    });
    ```

    ## In app.config.ts

    ```typescript
    import { Inject, Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Observable } from 'rxjs/Rx';
    @@ -81,23 +84,31 @@ export class AppConfig {
    });
    }
    }
    ```

    ## In env.json
    ```json
    {
    "env": "development"
    }
    ```

    ## In config.development.json
    ```json
    {
    "host": "localhost"
    }
    ```

    ## In config.production.json
    ```json
    {
    "host": "112.164.12.21"
    }
    ```

    ## In Any Angular2 class
    ```typescript
    import { AppConfig } from './app.config';

    export class AnyClass {
    @@ -109,3 +120,4 @@ export class AnyClass {
    let host:string = config.get('host');
    }
    }
    ```
  9. @fernandohu fernandohu created this gist Nov 2, 2016.
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,111 @@
    ## In Your Module

    import { APP_INITIALIZER } from '@angular/core';
    import { AppConfig } from './app.config';

    @NgModule({
    ...
    providers: [
    AppConfig,
    { provide: APP_INITIALIZER, useFactory: (config: AppConfig) => () => config.load(), deps: [AppConfig], multi: true }
    ],
    ...
    });

    ## In app.config.ts

    import { Inject, Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Observable } from 'rxjs/Rx';

    @Injectable()
    export class AppConfig {

    public static config: Object = null;
    public static env: Object = null;

    constructor(private http: Http) {

    }

    public static get(key: any) {
    return AppConfig.config[key];
    }

    public static getEnv(key: any) {
    return AppConfig.env[key];
    }

    /**
    * This method:
    * a) Loads "env.json" to get what is the current environment (e.g.: 'production', 'development')
    * b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
    */
    public load() {
    return new Promise((resolve, reject) => {
    if (AppConfig.config != null || AppConfig.env != null) {
    return resolve(true);
    }

    this.http.get('env.json').map( res => res.json() ).subscribe( (envResponse) => {
    AppConfig.env = envResponse;
    let request:any = null;

    switch (envResponse.env) {
    case 'production': {
    request = this.http.get('config.' + envResponse.env + '.json');
    } break;

    case 'development': {
    request = this.http.get('config.' + envResponse.env + '.json');
    } break;

    case 'default': {
    alert('Database adapter not defined');
    } break;
    }

    request
    .map( res => res.json() )
    .catch((error: any) => {
    console.error(error);
    reject(error);
    return Observable.throw(error.json().error || 'Server error');
    })
    .subscribe((responseData) => {
    AppConfig.config = responseData;
    resolve(true);
    });
    });

    });
    }
    }

    ## In env.json
    {
    "env": "development"
    }

    ## In config.development.json
    {
    "host": "localhost"
    }

    ## In config.production.json
    {
    "host": "112.164.12.21"
    }

    ## In Any Angular2 class
    import { AppConfig } from './app.config';

    export class AnyClass {
    constructor(private config: AppConfig) {

    }

    myMethod() {
    let host:string = config.get('host');
    }
    }