【问题标题】:How to use common service between modules?如何在模块之间使用公共服务?
【发布时间】:2020-12-15 01:33:21
【问题描述】:

如何为多个模块使用一个公共服务?

我有服务

@Injectable()
export class TestService {
  test(): number {
    return 123;
  }
}

我在 App 模块中注册了它。

  providers: [TestService],
  exports: [TestService]

我想在产品模块和其他模块中使用它。

@Module({
  imports: [TestService],
  controllers: [ProductsController],
  providers: [ProductsService]
})

在产品模块中使用

    constructor(
        @Inject('TestService')
        private readonly TService: TestService,
    ) {}

错误:

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

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    您应该导入 Appmodule 以使用 serviceTest:

        @Module({
      imports: [AppModule],
      controllers: [ProductsController],
      providers: [ProductsService]
    })
    

    但这不适用于循环依赖问题,更多信息请访问:circular-dependency

    所以解决方案是创建一个包含您想要共享的服务的共享模块并使用它们,您应该只导入模块而不是服务,exp:

     @Module({
      imports: [SharedModule],
      controllers: [ProductsController],
      providers: [ProductsService]
    })
    

    更多关于共享模块的信息shared-modules

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      相关资源
      最近更新 更多