0

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

我有服务

@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 */ ]
  })
4

1 回答 1

2

您应该导入 Appmodule 以使用 serviceTest:

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

但这不适用于循环依赖问题以获取更多信息,请访问:循环依赖

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

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

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

于 2020-12-14T09:48:18.367 回答