使用ClientsModule.registerAsync

问题描述

上下文是,我创建了一个共享的配置模块,该模块导入了多个配置模块,每个配置模块都在导出自己的服务,共享模块导出了每个导入的模块,目前在我的应用程序中,我有要导入的应用程序模块共享配置模块和导入共享配置模块的auth模块。

在项目中,我正在使用nestjs微服务,并且尝试使用ClientsModule方法注册registerasync来访问我的auth模块中的auth config服务。

目录体系结构:

/**
config/  
  - shared-config.module.ts
  - app/
     - app-config.service.ts
     - app-config.module.ts
  - auth/
     - auth-config.service.ts
     - auth-config.module.ts
  ... other config modules
- auth/
   - auth.module.ts
- app/
   - app.module.ts
*/

shared-config.module.ts:

@Module({
  imports: [AppConfigModule,MicroServiceAuthConfigModule,/* and other modules */],export: [AppConfigModule,/* and other modules */]
})
export class SharedConfigModule {}

auth-config.module.ts:

@Module({
    imports: [
        ConfigModule.forRoot({
           ... some config
        }),],providers: [MicroServiceAuthConfigService],exports: [MicroServiceAuthConfigService],})
export class MicroServiceAuthConfigModule {}

问题是我试图使用MicroServiceAuthConfigService在我的ClientsModule中创建AuthModule

auth.module.ts:

@Module({
  imports: [
    SharedConfigModule,ClientsModule.registerasync([
      {
        name: 'AUTH_PACKAGE',inject: [MicroServiceAuthConfigService],useFactory: (authConfigService: MicroServiceAuthConfigService) => ({
          transport: Transport.GRPC,options: {
            url: authConfigService.url,package: authConfigService.package,protoPath: authConfigService.protoPath,},}),]),controllers: [AuthController],providers: [AuthService],})
export class AuthModule {}

app.module.ts:

@Module({
  imports: [AuthModule,SharedConfigModule],})
export class AppModule {}

因为我已经导入了SharedConfigModule,所以我应该访问useFactory中的MicroServiceAuthConfigService,但是却出现以下错误

嵌套无法解析AUTH_PACKAGE(?)的依赖项。请做出来 确保索引[0]处的参数MicroServiceAuthConfigService为 在ClientsModule上下文中可用。

可能的解决方案:

  • 如果MicroServiceAuthConfigService是提供程序,它是否是当前ClientsModule的一部分?
  • 如果MicroServiceAuthConfigService是从单独的@Module导出的,那么该模块是否在ClientsModule中导入? @Module({ 导入:[/ *包含MicroServiceAuthConfigService的模块* /]})

奇怪的是,在我的应用模块中,我注入了SharedConfigModule,在文件main.ts中,我正在使用app.get(MicroServiceAuthConfigService),并且可以正常工作。

那我在做什么错了?

解决方法

在您的ClientsModule.registerAsync中,需要添加imports,其数组包含导出MicroServiceAuthConfigService提供程序的模块。看起来您特别需要

@Module({
  imports: [
    SharedConfigModule,ClientsModule.registerAsync([
      {
        name: 'AUTH_PACKAGE',imports: [MicroServiceAuthConfigModule],inject: [MicroServiceAuthConfigService],useFactory: (authConfigService: MicroServiceAuthConfigService) => ({
          transport: Transport.GRPC,options: {
            url: authConfigService.url,package: authConfigService.package,protoPath: authConfigService.protoPath,},}),]),],controllers: [AuthController],providers: [AuthService],})
export class AuthModule {}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...