如何在 Angular 6 中编辑环境变量而不重建? [英] How to edit environment variables without rebuild in Angular 6?

查看:21
本文介绍了如何在 Angular 6 中编辑环境变量而不重建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在 environment.ts 文件中设置我的 API URL.我必须将相同的构建部署到具有不同 API URL 的多个客户端.目前,我正在更改环境变量后进行单独的构建.

I usually set my API URLs in environment.ts file. I have to deploy the same build to multiple clients with different API URLs. Currently I am taking separate builds after changing the environment variables.

有没有办法在构建后编辑环境变量,这样我就可以为每个客户端提供相同的构建?

Is there any way to edit environment variables after build, so I can give the same build to each client?

推荐答案

我研究了这个问题,这是我不使用 environment.ts

I researched this issue and this is my solution without using environment.ts

我在 json 文件中定义了全局设置.因为如果我们在 ts 文件中定义,如果在生产模式下构建,很难找到改变值的常量.

I defined global settings in json file. Because if we defined in ts file, if build in production mode it is not easy to find constants to change value.

export class SettingService  {

  constructor(private http: HttpClient) {

  }



public getJSON(file): Observable<any> {
      return this.http.get("./assets/configs/" + file + ".json");
  }
  public getSetting(){
      // use setting here
  }
}

在 app 文件夹中,我添加文件夹 configs/setting.json

In app folder, i add folder configs/setting.json

setting.json 中的内容

Content in setting.json

{
    "baseUrl": "http://localhost:52555"
}

在应用模块中添加APP_INITIALIZER

 {
      provide: APP_INITIALIZER,
      useFactory: (setting: SettingService) => function() {return setting.getSetting()},
      deps: [SettingService],
      multi: true
    }

通过这种方式,我可以更轻松地更改 json 文件中的 baseUrl 值.

with this way, I can change baseUrl value in json file easier.

这篇关于如何在 Angular 6 中编辑环境变量而不重建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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