使用文件配置生产Angular应用程序

问题描述

我必须构建一个概念证明角度的应用程序,它将对应用程序(软件)进行API调用。 我的问题是我正在测试对本地应用程序的调用,而客户应用程序可能具有不同的设置:不同的入口点,不同的端口等。

我希望能够定义这些参数并从生产服务器上的文件中读取它们。 我读过有关使用环境文件的信息,但在构建应用程序之前必须进行设置。我希望以后能够做到。

解决方法

我终于发现这里是遵循的步骤: https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration

1。创建服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppConfigService {
  private appConfig;

  constructor(private http: HttpClient) { }

  loadAppConfig() {
    return this.http.get('/assets/data/appConfig.json')
      .toPromise()
      .then(data => {
        this.appConfig = data;
      });
  }

  getConfig() {
    return this.appConfig;
  }
}

** 2。将此服务导入app.module +创建一个初始化函数**

import { NgModule,APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './app-config.service';

const appInitializerFn = (appConfig: AppConfigService) => {
  return () => {
    return appConfig.loadAppConfig();
  };
};

@NgModule({
  ...
  providers: [
    AppConfigService,{
      provide: APP_INITIALIZER,useFactory: appInitializerFn,multi: true,deps: [AppConfigService]
    }
  ],...
})
export class AppModule { }

在我的app.component中:

constructor(private appConfig: AppConfigService) {
}
ngOnInit(): void {
  this.myConfig = this.appConfig.getConfig();
}

现在,我可以在模板中或应用程序中的任何位置显示配置数据。构建时,还会导出json文件,我们可以访问它!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...