Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Is it possible to read a json file after building

Tags:

angular

I am working on an angular 7 project which needs to be running on different servers. I need to read server URL from environment file and cannot set as a static variable.

I tried reading a JSON file but as soon as I ng build the project, it copies the content of JSON as static value in main.js

Is it possible to read a JSON file dynamically after building the project? Like reading from env.json which I can put after building the project

like image 981
Ashutosh Avatar asked Oct 16 '22 05:10

Ashutosh


1 Answers

I created a setting.json file in assets folder, after ng build I go to setting.json change back end url.

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
    }
like image 110
Hien Nguyen Avatar answered Nov 15 '22 08:11

Hien Nguyen