【问题标题】:NestJS. Can't inject a repository from a different module巢穴。无法从其他模块注入存储库
【发布时间】:2021-01-24 15:52:21
【问题描述】:

我正在尝试使用在另一个模块中定义的 typeorm 自定义存储库

关注documentation

如果您想在导入 TypeOrmModule.forFeature 的模块之外使用存储库,则需要重新导出由它生成的提供程序。您可以通过导出整个模块来做到这一点,如下所示:

@Module({
  imports: [TypeOrmModule.forFeature([Role])],
  exports: [TypeOrmModule]
})
export class RoleModule {}

现在如果我们在 UserHttpModule 中导入 UsersModule,我们可以在后一个模块的提供者中使用 @InjectRepository(User)。

就我而言:

@Module({
  imports: [RoleModule],
  providers: [UsersService],
  controllers: [UsersController]
})
export class UserModule {}

现在当我注入角色存储库时

export class UserService {
  constructor(@InjectRepository(Role) private roleRepository: Repository<Role>) {}
}

我有一个错误: Nest can't resolve dependencies of the UserService (?).

是我还是文档不正确? 有人可以建议这里的错误是什么或给出一个更正的例子吗?

【问题讨论】:

  • 我知道你已经接受了一个答案,但你得到的完整错误是什么?
  • [ExceptionHandler] Nest can't resolve dependencies of the UserService (?). Please make sure that the argument RoleRepository at index [1] is available in the UserModule context. Potential solutions: - If RoleRepository is a provider, is it part of the current UserModule? - If RoleRepository is exported from a separate @Module, is that module imported within UserModule? @Module({ imports: [ /* the Module containing RoleRepository */ ] })

标签: nestjs typeorm


【解决方案1】:

尝试将TypeOrmModule.forFeature([Role]) 添加到导入中:

@Module({
  imports: [TypeOrmModule.forFeature([Role]), RoleModule], // <-- here
  providers: [UsersService],
  controllers: [UsersController]
})
export class UserModule {}

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 2020-04-08
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多