【问题标题】:How to create service with Repository exports?如何使用存储库导出创建服务?
【发布时间】:2021-01-28 19:07:27
【问题描述】:

我使用多个存储库创建了服务:

@Injectable()
export class DataService {
    constructor(
        @InjectRepository(ClassicPrices, 'connect')
        private classicPrices: Repository<ClassicPrices>,

        @InjectRepository(ModernPrices, 'connect')
        private modernPrices: Repository<ModernPrices>,
    ) {}

    public pricesRepository(server): Repository<ModernPrices | ClassicPrices> {
        switch (server) {
            case 'modern':
                return this.modernPrices;
            case 'classic':
                return this.classicPrices;
        }
    }
}

数据模块设置:

@Module({
  imports: [
    TypeOrmModule.forFeature([
      ClassicPrices,
      ModernPrices
    ], 'connect'),
  ],
  providers: [DataService],
  exports: [DataService]
})
export class DataModule {}

当我在其他模块中使用它时^ 出现错误“Nest 无法解析 DataService (connect_ClassicPrices) 的依赖项。请确保索引 [2] 处的参数 connect_ClassicPrices 在 DataModule 上下文中可用。

可能的解决方案:

  • 如果 connect_ClassicPrices 是提供者,它是当前 DataModule 的一部分吗?
  • 如果 connect_ClassicPrices 是从单独的 @Module 导出的,那么该模块是否会导入 DataModule 中?
  @Module({
    imports: [ /* the Module containing  connect_ClassicPrices */ ]
  })

如何导出仓库?

【问题讨论】:

  • 你在另一个模块中导入DataModule吗?
  • 是的,我添加到导入 DateModule

标签: nestjs typeorm


【解决方案1】:

如果您想在其他模块中使用来自DataModule 的存储库,您需要将TypeOrmModule 添加到DataModule 中的导出数组中:

exports: [DataService, TypeOrmModule]

然后,任何导入DataModule 的模块都可以使用TypeOrmModule.forFeature 注册的存储库。通常,最好只导出服务并将存储库的范围限定在其模块内,因为这会使您的应用更加模块化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多