Completely external constants in Angular 5 using some configuration file

后端 未结 4 1073
小鲜肉
小鲜肉 2020-12-10 06:51

I have an app-const.ts with a server URL:

export class AppConst {
  public static serverPath = \'http://10.0.0.126:3031\';
}

This

4条回答
  •  [愿得一人]
    2020-12-10 07:12

    I used the assets folder to reference external configuration. The idea is that the deployment process updates the configuration for that environment into the assets folder which is then read on app startup. To do this, first place your configuration in src/app/assets/config.json. E.g.

    {
        "serverRoot":"https://my.server.root.com/"
    }
    

    The deployment process can then update the serverRoot property within this file to the correct value for that environment, or replace the contents of config.json entirely.

    Then, create a model class in src/app/model/environment.ts which will allow type safe access to the configuration:

    export class Environment {
        static serverRoot:string;
    
        static load(config:json) {
            this.serverRoot = config.serverRoot;
        }
    }
    

    Then, create a service to load the configuration in src/app/services/environment-load.service.ts:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Environment } from '../model/Environment';
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class EnvironmentLoadService {
    
      constructor(private http: HttpClient) { }
    
      init() {
        return this.http.get('assets/config.json').toPromise().then(data => {
          Environment.load(data);
        });
      }
    
      static initializeEnvironmentConfig = (appConfig: EnvironmentLoadService) => {
        return () => {
          return appConfig.init();
        };
      };
    }
    

    Finally, in your app module (src/app/app.module.ts), set the EnvironmentLoadService as a Provider which is created during the app initialization stage of the app's lifecycle. This guarantees all promises are resolved before the app initialization stage is complete and that your config is fully loaded before the first component is constructed:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, APP_INITIALIZER } from '@angular/core';
    import { AppComponent } from './app.component';
    import { HttpClientModule } from '@angular/common/http';
    import { EnvironmentLoadService } from './services/environment-load.service';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule
      ],
      providers: [EnvironmentLoadService, {
        provide: APP_INITIALIZER,
        useFactory: EnvironmentLoadService.initializeEnvironmentConfig,
        multi: true,
        deps: [EnvironmentLoadService]
      }],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

提交回复
热议问题