Where to save global settings in Angular 4

I have another way to define global settings. 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 value in json file easier.

I applied this in project for baseUrl, dateformat, sessiontimeout...


This answer is similar to @trichetriche, with few more details on the code.

For development/testing purpose

environment.ts

export const environment = {
  production: false,
  appUrl: 'localhost:4200'
};

For production

environment.prod.ts

export const environment = {
      production: true,
      appUrl: 'mywebsite.com'
    };

Usage

service.ts

import { environment } from '../../environments/environment';

this._http.get(environment.appUrl, requestHeaders(options));

Make a note of production parameter in all the environment files. I believe you could also create more environments like environment.unittesting.ts.


When I first started using Angular 2, I used a global.ts file where I'd put all my variables, so that I could change it easily.

I've then discovered the environments provided by angular CLI. All you have to do is name a file environment.prod.ts (for prod), and use ng build --prod when you build it. when you develop, use the environment.ts file and both files have to have the same variables.

I hope this answers your question.