Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit environment variables without rebuild in Angular 6?

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?

like image 273
Anoop Sankar Avatar asked Apr 11 '19 07:04

Anoop Sankar


People also ask

How does angular maintain different environments?

By default Angular application can be built to development environment or to production environment. Based on target environment, your application might have different setup. For example, API URL to fetch data from server.

Do we need to set environment variables for angular?

If you're building an app that uses an API, you'll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.


1 Answers

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.

like image 54
Hien Nguyen Avatar answered Sep 21 '22 23:09

Hien Nguyen