【问题标题】:How can I pass options to my AppModule with NestJS?如何使用 NestJS 将选项传递给我的 AppModule?
【发布时间】:2020-06-05 09:36:59
【问题描述】:

我想将我的 NestJS 应用程序用作我可以安装在另一个快速应用程序中的子应用程序。我希望能够将一些选项传递给我的 NestJS 应用程序。因此我创建了一个这样的挂载函数:

import { boot } from './boot';

export async function mount(app, mountPath: string, options) {
  const subApp = await boot(options)
  await subApp.init()

  app.use(mountPath, subApp.getHttpAdapter().getInstance());

  return app
}

开机功能如下:

import { NestFactory } from '@nestjs/core';
import { NestApplicationOptions } from '@nestjs/common';
import { AppModule } from './app.module';

export async function boot(options) {
  return NestFactory.create(AppModule, options);
}

问题:如何在我的模块中访问这些选项?我的 AppModule 目前看起来像这样:

@Module({
  imports: [
    ModuleA,
    MobuleB
  ],
})
export class AppModule {
}

将选项传递给 NestFactory 是完全错误的吗?我想用这些选项初始化我的应用程序,然后在我的模块中访问它们。

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    事实证明我可以为此使用动态模块并使用register 方法接收选项作为参数。

    https://medium.com/@enzo_volkmann/how-to-pass-configuration-into-your-nest-js-modules-1f883faca4f7

    https://docs.nestjs.com/fundamentals/dynamic-modules

    【讨论】:

      【解决方案2】:

      我认为最简单、最正统的做法是创建一个提供配置服务的配置模块。 然后,您可以根据需要对其进行初始化,并在任何地方使用它。

      您可以使用以下nestjs 官方模块:https://docs.nestjs.com/techniques/configuration 或创建您自己的模块。

      【讨论】:

        猜你喜欢
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 2021-11-13
        • 2021-01-30
        • 2011-03-13
        • 1970-01-01
        相关资源
        最近更新 更多