Inject nestjs service from another module

后端 未结 3 1820
青春惊慌失措
青春惊慌失措 2020-12-09 07:47

I\'ve got a PlayersModule and an ItemsModule.

I want to use the ItemsService in the PlayersService.

When

相关标签:
3条回答
  • 2020-12-09 08:07

    You have to export the ItemsService in the module that provides it:

    @Module({
      controllers: [ItemsController],
      providers: [ItemsService],
      exports: [ItemsService]
      ^^^^^^^^^^^^^^^^^^^^^^^
    })
    export class ItemsModule {}
    

    and then import the exporting module in the module that uses the service:

    @Module({
      controllers: [PlayersController],
      providers: [PlayersService],
      imports: [ItemsModule]
      ^^^^^^^^^^^^^^^^^^^^^^
    })
    export class PlayersModule {}
    

    ⚠️ Do not add the same provider to multiple modules. Export the provider, import the module. ⚠️

    0 讨论(0)
  • 2020-12-09 08:08

    I believe that you faced the same problem i had. My scenario was 2 sibling custom modules (user, auth) that needed to use each other's services. I used circular DI to solve it. please check this link

    Let me know whether if it solved your issue, maybe I can advise you further.

    0 讨论(0)
  • 2020-12-09 08:17

    I solved this problem my removing @Inject() from the argument in my constructor that was passing the exported service.

    0 讨论(0)
提交回复
热议问题