Nestjs 如何在模块之间使用公共服务?

Nestjs 如何在模块之间使用公共服务?,nestjs,Nestjs,如何为多个模块使用公共服务 我有服务 @Injectable() export class TestService { test(): number { return 123; } } 我在应用程序模块中注册了它 providers: [TestService], exports: [TestService] 我想在产品模块和其他模块中使用它 @Module({ imports: [TestService], controllers: [ProductsCon

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

我有服务

@Injectable()
export class TestService {
  test(): number {
    return 123;
  }
}
我在应用程序模块中注册了它

  providers: [TestService],
  exports: [TestService]
我想在产品模块和其他模块中使用它

@Module({
  imports: [TestService],
  controllers: [ProductsController],
  providers: [ProductsService]
})
在产品模块中使用

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

  • 如果TestService是一个提供者,它是当前ProductsModule的一部分吗
  • 如果TestService是从单独的@Module导出的,那么该模块是否在ProductsModule中导入

您应该导入Appmodule以使用serviceTest:

    @Module({
  imports: [AppModule],
  controllers: [ProductsController],
  providers: [ProductsService]
})
但这对循环依赖性问题不起作用,请访问更多信息:

因此解决方案是创建一个共享模块,其中包含您想要共享的服务,要使用这些服务,您应该只导入模块而不是服务,exp:

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

有关共享模块的更多信息

您应该导入Appmodule以使用serviceTest:

    @Module({
  imports: [AppModule],
  controllers: [ProductsController],
  providers: [ProductsService]
})
但这对循环依赖性问题不起作用,请访问更多信息:

因此解决方案是创建一个共享模块,其中包含您想要共享的服务,要使用这些服务,您应该只导入模块而不是服务,exp:

 @Module({
  imports: [SharedModule],
  controllers: [ProductsController],
  providers: [ProductsService]
})
有关共享模块的更多信息