未定义向 CQRS 中注入的 nestjs 服务

Injected nestjs service in to CQRS is undefined

我有一个服务要在 CQRS 中导入,但在运行时,服务方法出现错误

构造函数中声明的服务,并在执行方法中使用它

@CommandHandler(UpdateSensorsProductsCommand)
export class UpdateSensorsProductsCommandHandler implements ICommandHandler<UpdateSensorsProductsCommand>
{
  constructor(
    private eventBus: EventBus,
    private sensorProductListService: SensorProductsListService,
  ) {}

  async execute(
    command: UpdateSensorsProductsCommand,
  ) {
    // I get this error: TypeError: Cannot read property 'getAllSensorsProducts' of undefined
    this.sensorProductListService.getAllSensorsProducts()
  }
}

并且我在名为 SystemCqrsModule

的 CQRS 模块中导入了 sensorProductListService 模块
@Module({
  imports: [
    CqrsModule,
    SensorProductsListModule,
  ],
    ...
  exports: [CqrsModule],
})
export class SystemCqrsModule {}

并从 sensorProductListModule 导出 sensorProductListService

this is sensorProductListModule

@Module({
  providers: [SensorProductsListService, UnitConvert],
  exports: [SensorProductsListService],
})
export class SensorProductsListModule {}

所以我有这个错误

TypeError: Cannot read property 'getAllSensorsProducts' of undefined

为什么我会收到这个错误?

如果您使用 request 范围内的 class 注入到您的服务中,那是行不通的。

您应该删除 request 范围内的依赖项或使用 moduleRef 处理它。参见 here