For modern Angular projects (version 2+), you need to maintain a config.json file per every environment: dev, staging or production.

If you normally import or require this file in your environment.ts file(s) it would be merged as part of your bundle and may not be editable by admins who need to edit them in new clusters.

src/app/app.module.ts

  import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

import ConfigService from '../services/config.service';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    ConfigService,
    ConfigService.getAppInitializer('/assets/config.json')
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

src/services/config.service.ts

  import { Injectable, APP_INITIALIZER } from "@angular/core";
import { HttpClient } from "@angular/common/http";

function getHostUrl() {
    return '//'+location.host;
}

@Injectable()
export default class ConfigService {

    public config: any;

    constructor(private http: HttpClient) {
    }

    load(path: string) {
        return new Promise((resolve, reject) => {
            this.http.get(getHostUrl()+path)
                .subscribe(data => {
                    this.config = data;
                    resolve(true);
                })
        });
    }

    static getAppInitializer(path: string) {
        return {
            provide: APP_INITIALIZER,
            useFactory: (config: ConfigService) => () => config.load(path),
            deps: [ ConfigService ],
            multi: true
        };
    }
}

Usage in another service

src/services/users.service.ts

  import { Injectable } from "@angular/core";

import ConfigService from '../services/config.service';
import { HttpClient } from "@angular/common/http";

@Injectable()
export default class UsersService {

  public config;

  constructor(private configService: ConfigService, private http: HttpClient) {
    this.config = this.configService.config;
  }

  getUsers() {
    return this.http.get(this.config.apiUrl + '/users')
  }
}

Usage of service in component

src/app/app.component.ts

  import { Component } from '@angular/core';

import ConfigService from '../services/config.service';
import UsersService from '../services/users.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';

  public config;
  public users: any[];

  constructor(private configService: ConfigService, private usersService: UsersService) {
    this.config = configService.config;
  }

  loadUsers() {
    this.usersService.getUsers()
      .subscribe((users: any[]) => this.users = users);
  }
}

Preview in StackBlitz

Edit in StackBlitz


186 0 0