你可以将配置文件以JSON格式放在资产文件夹中,并动态检索。确保在应用程序启动之前检索它,这样当组件/服务需要时,它就可以使用。为此,您可以使用APP_INITIALIZER令牌。
步骤1:将您的JSON配置文件放置在src/assets/config/conf.json下(JSON格式,不是TS格式,因为在生产模式中没有TS编译器)。
步骤2:添加一个新的配置服务。
import {Inject, Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from 'rxjs/Rx';
import {environment} from "../../environments/environment";
export class AppConfig
{
readonly apiEndpoint: string;
}
export let APP_CONFIG: AppConfig;
@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();
APP_CONFIG = Object.assign(t, envResponse);
resolve(true);
});
});
}
}
步骤 #3: 在您的主模块中,在声明模块之前添加以下内容
export function loadConfigService(configService: AppConfigService): Function
{
return () => { return configService.load() };
}
第四步:修改模块提供者以添加此内容。
providers: [
…
AppConfigService,
{ provide: APP_INITIALIZER, useFactory: loadConfigService , deps: [AppConfigService], multi: true },
],
步骤五: 在你的代码中使用配置文件
import {APP_CONFIG} from "../services/app-config.service";
return APP_CONFIG.configXXX;
现在,您可以将应用程序交付给多个客户端;每个客户端只需要在conf.json文件中有自己的特定参数。