Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Config JSON File In Angular 2

I want to load Constant File in Angular 2(which is a Normal TypeScript File) having WebAPI EndPoints. In Angular1.x. we used to have constants for the same. How in Angular 2 I can Implement the Same?

I have created the .ts file.My main concern lies in how to load the file beforehand every Other class File loads.

.ts file :

export class testAPI {
     getAPI = "myUrl";
}

In service file I am using the same by doing Normal Import:

constructor(private http: Http) { 

      //console.log(this.test);
      console.log(this.testing.getAPI);
      //this.test.load();
    }

I am getting the Console as Undefined.(Must be because my Service class is loading before API Class).

Thanks in Advance.

like image 781
Avinash Avatar asked Feb 08 '17 10:02

Avinash


People also ask

What is config JSON file in Angular?

A file named angular. json at the root level of an Angular workspace provides workspace-wide and project-specific configuration defaults for build and development tools provided by the Angular CLI. Path values given in the configuration are relative to the root workspace folder.

Where is config JSON in Angular?

You can have the JSON file somewhere in assets folder like: assets/config . Depending on whether the environment is dev or not you can use two . json files, one for development and one for production.


1 Answers

UPDATES

Inspired with the solution for this particular problem created ngx-envconfig package and published it on NPM registery. It has the same functionalities as it is provided in this answer and even more.


You can have the JSON file somewhere in assets folder like: assets/config. Depending on whether the environment is dev or not you can use two .json files, one for development and one for production. So you can have development.json and production.json files, where each one will keep the appropriate API endpoints.

Basically you need to go through the following steps:

1. Setting up environment (skip this step if you have it already)

Create two files in src/environments folder:

environment.prod.ts

export const environment = {
  production: true
};

environment.ts

export const environment = {
  production: false
};

2. Create JSON config files

assets/config/production.json

{
  "debugging": false,

  "API_ENDPOINTS": {
    "USER": "api/v1/user",
    ...
  }
}

assets/config/development.json

{
  "debugging": true,

  "API_ENDPOINTS": {
    "USER": "api/v1/user",
    ...
  }
}

3. Create a service as follows

Note depending on the environment, the ConfigService will load the appropriate file

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

import { environment } from 'environments/environment'; //path to your environment files

@Injectable()
export class ConfigService {

    private _config: Object
    private _env: string;

    constructor(private _http: Http) { }
    load() {
        return new Promise((resolve, reject) => {
            this._env = 'development';
            if (environment.production)
                this._env = 'production';
            console.log(this._env)
            this._http.get('./assets/config/' + this._env + '.json')
                .map(res => res.json())
                .subscribe((data) => {
                    this._config = data;
                    resolve(true);
                },
                (error: any) => {
                    console.error(error);
                    return Observable.throw(error.json().error || 'Server error');
                });
        });
    }
    // Is app in the development mode?
    isDevmode() {
        return this._env === 'development';
    }
    // Gets API route based on the provided key
    getApi(key: string): string {
        return this._config["API_ENDPOINTS"][key];
    }
    // Gets a value of specified property in the configuration file
    get(key: any) {
        return this._config[key];
    }
}

export function ConfigFactory(config: ConfigService) {
    return () => config.load();
}

export function init() {
    return {
        provide: APP_INITIALIZER,
        useFactory: ConfigFactory,
        deps: [ConfigService],
        multi: true
    }
}

const ConfigModule = {
    init: init
}

export { ConfigModule };

4. Integrate with app.module.ts

import { NgModule } from '@angular/core';
import { ConfigModule, ConfigService } from './config/config.service';

@NgModule({
    imports: [
        ...
    ],
    providers: [
        ...
        ConfigService,
        ConfigModule.init(),
        ...
    ]
})

export class AppModule { }

Now you can use ConfigService wherever you want get the necessary API endpoints defined in config .json files.

like image 65
Karlen Avatar answered Sep 21 '22 17:09

Karlen