Krishnan
Krishnan

Reputation: 1008

How do i read the config files entries in angular 2?

I need to read the config file which is in a json format. the json file contains config entries in key/pair values. How do I get the values of any particular key?

My question is, I can read the json file on a whole using http.get() or any other way, but how do i get a particular config value based on a key? should i need to loop thru/iterate the items to get the required item or is there any other better ways to do it?

my json config looks like below

{
  "SecurityService": "http://localhost/SecurityAPI",
  "CacheService": "http://localhost/CacheServiceAPI"
}

I tried do the code changes as per your suggestion The code to read the config data from the json file

getConfiguration = (): Observable<Response> => {
        return this.http.get('config.json').map(res => res.json());
    }

following code to invoke the above method from the calling component and use the read config values

this._ConfigurationService.getConfiguration()
            .subscribe(
            (res) => {
                this.configs = res;
                console.log(this.configs);
            },
            (error) => console.log("error : " + error),
            () => console.log('Error in GetApplication in Login : ' + Error)
        );

But when the above is getting executed, I am getting the error as

"error : SyntaxError: Unexpected token < in JSON at position 0"

what is the mistake I am doing here, the same code to read the json file works in other scenarios where I need to read data from json and bind the grid etc.

I have tried reproducing the issue in plunkr https://plnkr.co/edit/rq9uIxcFJUlxSebO2Ihz?p=preview

Upvotes: 9

Views: 19885

Answers (2)

Durga Gonnade
Durga Gonnade

Reputation: 11

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

...
//Add this function as initiating load method first
function initConfig(config: AppConfig){
    return () => config.load()
}
@NgModule({
    imports: [
        ...
        HttpModule
    ],
    ...
    providers: [
        ...
        AppConfig,
        { provide: APP_INITIALIZER, useFactory: initConfig, deps: [AppConfig], multi: true }
    ],
    ...
});
export class AppModule { 
...
}




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('environment');
    }
}

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

@Injectable()
export class AppConfig {

    private config: Object = null;
    private environment:    Object = null;

    constructor(private http: Http) {

    }

    /**
     * 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 (environment file)
     */
    public getEnv(key: any) {
        return this.environment[key];
    }

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

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

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

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

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

        });
    }
}

Upvotes: 0

eko
eko

Reputation: 40647

"Reading" a config file is not different from reading any other object in js. For example, create a config variable:

export var config = {
  title: "Hello World",
  "SecurityService":"http://localhost/SecurityAPI",
  "CacheService":"http://localhost/CacheServiceAPI"
}

and then import it to your component to use it like this:

import { Component, Input } from '@angular/core';
import { config } from './config';

@Component({
  selector: 'my-app',
  template: `{{myTitle}}<br>{{security}}<br> {{cache}}`,
  directives: []
})
export class AppComponent {
    myTitle = config.title;
    security = config.SecurityService;
    cache = config.CacheService;

}

Full example: https://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=preview

Upvotes: 17

Related Questions