我认为这里不需要动态模块。
实际上,只需要从您的 AuthModule 中导出您想要注入到由 NestJs 管理的其他实体的服务,并在您希望其他实体注入您的 AuthService 的模块中导入 AuthModule。
import { Module } from '@nestjs/common'
import { AuthService } from './AuthService'
@Module({
providers: [
AuthService,
// ... others
],
exports: [
AuthService
]
})
export class CommonModule {}
然后在您的依赖类(假设是另一个控制器,但可以是 GraphQL 解析器、拦截器或其他任何东西)中,您声明对 AuthService 的依赖。
import { AuthService } from '../auth/AuthService'
import { Dependencies } from '@nestjs/common'
@Dependencies(AuthService)
export class DependentController {
constructor (authService) {
this.authService = authService
}
}
最后,为了 AuthService 对依赖的控制器可用,它必须被导入到提供控制器的同一个模块中。
import { Module } from '@nestjs/common'
import { CommonModule } from '../auth/CommonModule'
import { DependentController } from './controller/DependentController'
@Module({
imports: [
CommonModule,
// ...others
],
providers: [
DependentController,
// ...others
]
})
export class ControllerModule {}
我知道语法可以更短,并且在打字稿中不使用依赖装饰器,但是问题的核心是从它提供的模块中导出共享服务,然后将该模块导入到模块中其他需要它的类中。