Created
May 9, 2018 19:22
-
-
Save scriptmaster/c5df9d5345daca003ba58437d3c257dc to your computer and use it in GitHub Desktop.
Maintain (per environment) config.json and load before your Angular components and services load
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment