12

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Anoop Sankar
  • 619
  • 5
  • 16
  • 2
    See https://github.com/angular/angular-cli/issues/7506 and the issues it links to. There are other ways to achieve runtime configuration, the environment feature is for build time config https://angular.io/guide/build#configuring-application-environments. – jonrsharpe Apr 11 '19 at 07:12

1 Answers1

11

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.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • This helped me! The only thing I would add is that in the place that says '// use setting here', you can assign the value of `this.getJson('setting').subscribe(url => this.somevariable = url)`. Then you can use that variable in your components injecting the `SettingService`. I struggled with this thought process, but eventually succeeded with this answer. Thank you. – sebaLinares Sep 25 '19 at 19:15
  • This is essentially what we are doing too. I came here looking to see if anyone else had come up with a better solution. We built into our build and deploy pipeline the ability to swap out the config file when deploying to a target as well. – crush Mar 23 '20 at 01:04
  • @Hien Nguyen:sir once above procedure is done....we have upload only config file in the server instead of whole build am i correct? – Kapil Soni Jun 10 '21 at 10:38
  • @Kapil yes, only setting.json file need – Hien Nguyen Jun 11 '21 at 01:02