你可以做什么它在assets文件夹中以json格式托管配置文件并动态检索它。您需要确保在应用程序启动之前检索它,这样它就可以在需要时在组件/服务中使用。为此,您可以使用 APP_INITIALIZER 令牌
步骤#1:将你的json配置文件放在src/assets/config/conf.json下(json格式,不是ts格式,因为prod模式下没有TS编译器)
第 2 步:添加新的配置服务
import {Inject, Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from 'rxjs/Rx';
import {environment} from "../../environments/environment";
/**
* Declaration of config class
*/
export class AppConfig
{
//Your properties here
readonly apiEndpoint: string;
}
/**
* Global variable containing actual config to use. Initialised via ajax call
*/
export let APP_CONFIG: AppConfig;
/**
* Service in charge of dynamically initialising configuration
*/
@Injectable()
export class AppConfigService
{
constructor(private http: HttpClient)
{
}
public load()
{
return new Promise((resolve, reject) => {
this.http.get('/assets/config/config.json').catch((error: any): any => {
reject(true);
return Observable.throw('Server error');
}).subscribe((envResponse :any) => {
let t = new AppConfig();
//Modify envResponse here if needed (e.g. to ajust parameters for https,...)
APP_CONFIG = Object.assign(t, envResponse);
resolve(true);
});
});
}
}
第 3 步:在您的主模块中,在声明模块之前添加此内容
/**
* Exported function so that it works with AOT
* @param {AppConfigService} configService
* @returns {Function}
*/
export function loadConfigService(configService: AppConfigService): Function
{
return () => { return configService.load() };
}
步骤#4:修改模块提供程序以添加此
providers: [
…
AppConfigService,
{ provide: APP_INITIALIZER, useFactory: loadConfigService , deps: [AppConfigService], multi: true },
],
第 5 步:在您的代码中,使用配置
import {APP_CONFIG} from "../services/app-config.service";
//…
return APP_CONFIG.configXXX;
现在,您可以将应用发送给多个客户;每个客户端只需要在 conf.json 文件中有他们的特定参数