我想在运行时从 json 文件加载配置变量以构建我的 Angular 应用程序
我在 src 目录中创建了我的 json 文件 app.conf.json,它包含:
{
"API_URL": "http://localhost/backend/",
"SERVER_URL": "http://localhost/MyApp/assets/uploads"
}
我创建了一个抽象类 AppConfig :
export abstract class AppConfig {
API_URL: string;
SERVER_URL: string;
}
我创建了服务
import { Injectable } from '@angular/core';
import {AppConfig} from './app-config';
import {HttpClient} from '@angular/common/http';
// to stock data
declare var window: any;
@Injectable({
providedIn: 'root'
})
export class JsonAppConfigService extends AppConfig {
constructor(private httClient: HttpClient) {
super();
}
/** Cette fonction va retourner une promise (charger le fichier app.config.json
* depuis le repertoire src du frontend
*/
load() {
return this.httClient.get<AppConfig>('app.config.json')
.toPromise()
.then(data => {
this.API_URL = data.API_URL;
this.SERVER_URL = data.SERVER_URL;
this.ldaps = data.ldaps;
window.config = data;
console.log(window.config);
})
.catch(() => {
console.log('Erreur : le fichier de configuration ne peut pas être chargé ');
});
}
}
在 app.module.ts 之后,我创建了提供程序:
export function appInitializer(jsonAppConfigService: JsonAppConfigService) {
return () => {
return jsonAppConfigService.load();
};
}
providers [ ...,
{ provide: AppConfig, deps: [HttpClient], useExisting: JsonAppConfigService},
{ provide: APP_INITIALIZER, deps: [JsonAppConfigService], useFactory: appInitializer,
multi: true},
]
现在我的文件已加载,我想将数据(window.config)传递给我的 environment.ts 文件,为此我创建了一个可以扩展环境的类:
declare var window: any;
export class DynamicEnvironment {
public get environment() {
return window.config;
}
}
在我的 envronment.ts 文件中:
import { DynamicEnvironment } from './dynamic-environment';
class Environment extends DynamicEnvironment {
public production: boolean;
constructor() {
super();
this.production = false;
}
}
export const environment = new Environment();
console.log(environment);
问题就在这里,我无法将数据获取到环境文件,我不知道为什么,或者错误在哪里?它在我的窗口变量中吗?还是有另一种方法来获取环境文件中的数据?
非常感谢您的帮助