Inject nestjs service from another module Inject nestjs service from another module typescript typescript

Inject nestjs service from another module


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. ⚠️


Let' say you want to use AuthService from AuthModule in my TaskModule's controller

for that, you need to export authService from AuthModule

@Module({    imports: [     ....    ],    providers: [AuthService],    controllers: [AuthController],    exports:[AuthService]  })export class AuthModule {}  

then in TaskModule, you need to import AuthModule (note: import AuthModule not the AuthService in TaskModule)

@Module({    imports:[      AuthModule    ],    controllers: [TasksController],    providers: [TasksService]  })export class TasksModule {}

Now you should be able to use DI in TaskController

@Controller('tasks')export class TasksController {   constructor(private authService: AuthService) {}   ...}  


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