Where to save global settings in Angular 4

Angular (Script Type) has many configuration files. What is the correct way to save global settings?

For example, when I call the API from local, then mine rootUrlis localhost:42000, but it should be when switching to production http:www.someting.com.

I want to save this rootUrlin some global place, so if I switch to production, then I only change in that rootUrl.

Please tell me where I should save these global settings, the same as web.config in Asp.Net.

+9
source share
4 answers

This answer is similar to @trichetriche, with a few details about the code.

For development/testingpurposes

environment.ts

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

production

environment.prod.ts

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

service.ts

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

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

production environment. , , environment.unittesting.ts.

+8

Angular 2, global.ts, , .

, CLI Angular. , , environment.prod.ts ( prod) ng build --prod . environment.ts, .

, .

+3

process.env webpack. .

/**
 * This interface makes sure we don't miss adding a property to both `prod` and `test`
 */
interface Config {
  someItem: string;
}

/**
 * We only export a single thing. The config.
 */
export let config: Config;

/**
 * `process.env.NODE_ENV` definition is driven from webpack
 *
 * The whole `else` block will be removed in the emitted JavaScript
 *  for a production build
 */
if (process.env.NODE_ENV === 'production') {
  config = {
    someItem: 'prod'
  }
  console.log('Running in prod');
} else {
  config = {
    someItem: 'test'
  }
  console.log('Running in test');
}

process.env.NODE_ENV webpack -p --define process.env.NODE_ENV='\"production\"' --config ./src/webpack.config.js

https://basarat.gitbooks.io/typescript/docs/tips/build-toggles.html

0

I have another way to define global settings. Because, if we defined ts in the file, if we build in production mode, it is not so easy to find constants for changing the 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 the application folder, I add the configs / setting.json folder

Content in setting.json

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

In the application module add APP_INITIALIZER

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

that way I can change the value in the JSON file easier.

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

0
source

Source: https://habr.com/ru/post/1677815/


All Articles