【问题标题】:In Angular how to Create a Configurable Property file to read a property, in production environment?在 Angular 中,如何在生产环境中创建可配置的属性文件来读取属性?
【发布时间】:2019-07-23 21:04:48
【问题描述】:

在我的应用程序中,我创建了 appMessages.ts,其中包含如下变量:

export const appMessages = {
    my_url: 'http://localhost:8080/myApp',
}

我基本上是用它来进行 REST 调用。在实际生产环境中,变量值不断变化,需要可配置。如果我使用 appMessages.ts,并创建一个生产包,使用

ng build --prod

问题是,appMessages.ts 不再是可配置的。是否有 Angular 方法来创建可配置的属性文件,可以根据当前的开发环境使用“my_url”动态配置?

可以在产品部署后读取某种属性文件吗?

【问题讨论】:

  • 为什么该变量在生产环境中会发生变化?那应该是保存在环境文件中的东西。但是,是的,您可以将其存储在 json 文件或数据库中,并在应用加载时获取它以供使用。
  • 具体来说,端口号是可以在不同环境中改变的东西。另外,我不能使用 dB(仅仅是因为 dB 的变化会在我的项目中产生很大的变化)。
  • 包含此信息的 json 文件可能是您最好的选择。但是您仍然需要更新 Angular 代码以在应用加载时获取 json。
  • 更新方式?我正在使用 Angular 5。您能否提供一个链接,其中包含相同的示例?
  • 您的应用程序不是从本地变量中提取(在捆绑过程中捆绑),而是从您的应用程序中删除变量。这意味着您的应用要使用它,您必须获取该变量(从外部 json 文件)。这是一个现有的SO question,关于如何在应用加载时进行 api 调用

标签: angular


【解决方案1】:

您可以在 src 目录中创建以下 config.json,然后使用 APP_INITIALIZER 提供程序。

{
    "myUrl": "http://172.22.251.207:20235"
}

app.module.ts

...
export function initConfig(config: AppConfigService) {
  return () => config.load();
}
...
providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initConfig,
      deps: [AppConfigService],
      multi: true
    }]
...

app-config.service.ts

@Injectable({
    providedIn: 'root'
})
export class AppConfigService {
    private config: Config = null;
    public configSubject: Subject<any> = new Subject<any>();

    constructor(private http: HttpClient) { }

    public load() {
        return this.http.get(environment.deployUrl + 'config.json')
            .toPromise()
            .then((config: any) => {
                this.config = config;
                this.configSubject.next(this.config);
            })
            .catch((err: any) => {
                console.error('ERROR: ' + err);
            })
    }

    getMyUrl() {
        return this.config.myUrl;
    }
}

export class Config {
    myUrl: string;
}

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2020-03-06
    • 2014-05-21
    • 2017-12-04
    • 2015-12-30
    • 1970-01-01
    • 2018-10-10
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多