在运行时使用 App_Initializer 从 .json 文件角度加载配置变量

问题描述

我想在运行时从 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);

而问题就在这里,我无法将数据获取到环境文件中,不知道为什么,或者错误在哪里?它在我的窗口变量中吗?或者有其他方法可以获取环境文件中的数据?

非常感谢您的帮助 问候

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)