简体   繁体   English

如何将环境配置注入不同的Angular模块?

[英]How to inject environment config to different Angular Modules?

I have a app.config.ts in my angular app that look something like this: 我在我的角应用程序中有一个app.config.ts,看起来像这样:

export const APP_CONFIG = {
   ....
}

This is generated on webpack build. 这是在webpack构建中生成的。

Now I have different angular modules that are on separate repository which is being used by my angular app. 现在我有了不同的角度模块,它们位于我的角度应用程序正在使用的独立存储库中。 Some of these modules also needs the environment configs defined in app.config.ts. 其中一些模块还需要app.config.ts中定义的环境配置。 I am installing these modules using NPM so they are found in node_modules folder. 我正在使用NPM安装这些模块,因此可以在node_modules文件夹中找到它们。

My problem is how am I going to supply the environment config to these modules without creating a dependency to the App itself? 我的问题是如何在不创建对应用程序本身的依赖性的情况下为这些模块提供环境配置?

I am thinking of saving the config to a global variable or saving it to localStorage on bootstrap of the app. 我正在考虑将配置保存到全局变量或将其保存到应用程序的引导程序上的localStorage。

Should I also create environment configs on each module? 我还应该在每个模块上创建环境配置吗? Then handle it on webpack build? 然后在webpack build上处理它?

Any ideas would be much appreciated. 任何想法将不胜感激。

If I understand your question, you need to pass configuration information from your main application to your own external Angular libraries. 如果我理解您的问题,您需要将配置信息从主应用程序传递到您自己的外部Angular库。 You can do that using the forRoot methodology explained in the Angular docs here . 您可以使用此处 Angular文档中介绍的forRoot方法执行此操作

Inside of your external Angular library modify the main exported module to have this structure: 在外部Angular库内部修改主导出模块以具有此结构:

export class MyLibraryModule {
  static forRoot(config: configData): ModuleWithProviders {
    return {
      ngModule: MyLibraryModule,
      providers: [
        {provide: AppConfigModel, useValue: config }
      ]
    };
  }

  constructor(@Optional() config: AppConfigModel) {
    if (config) { /* Save config data */ }
  }

 }

When you import this module into your application, use the forRoot static method and pass in the config data. 将此模块导入应用程序时,请使用forRoot静态方法并传入配置数据。 You will need to create the appropriate model in your libarary (AppConfigModel in my example) to receive the APP_CONFIG you are passing in the forRoot method. 您需要在libarary中创建适当的模型(在我的示例中为AppConfigModel),以接收您在forRoot方法中传递的APP_CONFIG。

imports: [
    MyLibraryModule.forRoot(APP_CONFIG),
 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM