How to edit environment variables without rebuild in Angular 6?

↘锁芯ラ 提交于 2020-08-21 06:34:26

问题


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?


回答1:


I researched this issue and this is my solution without using environment.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
  }
}

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

Content in setting.json

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

In app module add APP_INITIALIZER

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

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



来源:https://stackoverflow.com/questions/55626547/how-to-edit-environment-variables-without-rebuild-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!