在Angular 2中加载配置JSON文件 [英] Load Config JSON File In Angular 2

查看:169
本文介绍了在Angular 2中加载配置JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在具有WebAPI端点的Angular 2中加载常量文件(这是一个普通的TypeScript文件). 在Angular1.x中.我们曾经有相同的常数. 如何在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?

我已经创建了.ts文件.我主要关心的是如何在每个其他类File加载之前预先加载该文件.

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

.ts文件:

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

我将控制台的状态设为Undefined.(一定是因为我的Service类在API类之前加载).

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

预先感谢.

推荐答案

更新

灵感来自此特定问题的解决方案,创建了 ngx-envconfig 程序包并将其发布在NPM注册.它具有与该答案中提供的功能相同的功能,甚至更多.

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.

您可以在Assets文件夹中的某个位置放置JSON文件,例如:assets/config.根据环境是否为开发人员,您可以使用两个.json文件,一个用于开发,一个用于生产.因此,您可以拥有development.jsonproduction.json文件,其中每个文件将保留适当的API端点.

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:

src/environments文件夹中创建两个文件:

Create two files in src/environments folder:

environment.prod.ts

environment.prod.ts

export const environment = {
  production: true
};

environment.ts

environment.ts

export const environment = {
  production: false
};

2.创建JSON配置文件

assets/config/production.json

2. Create JSON config files

assets/config/production.json

{
  "debugging": false,

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

assets/config/development.json

assets/config/development.json

{
  "debugging": true,

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

3.如下创建服务

注意,具体取决于环境,ConfigService将加载适当的文件

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.与app.module.ts集成

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

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

export class AppModule { }

现在,您可以在需要获取配置.json文件中定义的必要API端点的任何地方使用ConfigService.

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

这篇关于在Angular 2中加载配置JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆