【问题标题】:Environment Specific File in Angular 2+Angular 2+ 中的环境特定文件
【发布时间】:2018-02-13 14:37:05
【问题描述】:

我们在一个应用程序中有一个文件,它位于

此文件包含所有常量,服务 URL,在整个应用程序中使用。 现在我的问题是,当我们的环境从开发更改为 QA 或生产时,我们需要更改此文件。

我们有什么方法可以在 Angular 2+ 中处理这个问题吗?通过为特定环境创建一个单独的常量文件?

【问题讨论】:

标签: angular


【解决方案1】:

如果您使用的是 Angular CLI,那么您将拥有两个文件 environment.ts 和 environment.prod.ts。您可以使用这些文件来存储您的常量。 在正常的构建环境中使用.ts。但是当您使用

创建构建时
ng build --prod

在这种情况下将使用environment.prod.ts

【讨论】:

  • 重点是,我们需要复制这些文件中的所有url吗?如果是,在这种情况下,我们需要更改我们正在导入应用常量文件的整个应用程序
  • 如果是这种情况,您可以遵循以下方法:1. 将您的常量导入这些 environement.ts 文件。 2. 将此环境文件导入您的 app.constants.ts,然后将其导出到必需的类型,这样您就不必更改代码中的其他任何地方。
【解决方案2】:

对于配置文件,我很久以前找到了一个教程(但适用于“.json”文件)

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


@Injectable()
export class ArchConfigurationService {
    private config: Object = null;
    private env:    Object = null;

  constructor (
    private http: Http,
  ) { }

    /**
    * Permite recuperar una propiedad en concreto.
    * Normalmente será una string, pero tambien puede ser un objeto
    * @param key La propiedad a buscar en la configuración.
    */
    public getProperty(key: string): any {
        return this.config[key];
    }

    /**
     * Obtain the env.
     */
    public getEnv(): string {
        return this.env['env'];
    }

    /**
     * Loads the "env.json" to obtain the env (Ej: 'production', 'development' )
     *  Then for this env loads the "[env].config.json"  (Ej: 'development.config.json')
     */
    public load() {
        return new Promise((resolve, reject) => {
            this.http.get('./enviroments/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 || 'Server error');
            }).subscribe( (envResponse) => {
                this.env = envResponse;
                let request:any = null;
                let enviro = this.getEnv();
                switch (enviro) {
                    case 'production': 
                        request = this.http.get('/enviroments/' + enviro + '.config.json');
                    break;

                    case 'development': 
                        request = this.http.get('./enviroments/' + enviro + '.config.json');
                    break;

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

        });
    }
  }

env.json

{
  "env": "development"
}

还有 development.config.json

{
   "url": ...
}

如果你想在应用程序中使用加载(否则使用“加载”)

import { ArchConfigurationService } from './services/arch.configuration.service';

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

【讨论】:

    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 2016-08-30
    • 1970-01-01
    • 2018-03-09
    • 2017-02-25
    相关资源
    最近更新 更多