typescriptnestjs

Injecting nested services


I have this folder structure:

.
├── lib/
│   └── dma/
│       ├── modules/
│       │   └── cmts/
│       │       ├── cmts.module.ts
│       │       └── cmts.service.ts
│       └── dma.module.ts
└── src/
    ├── app.module.ts
    └── app.service.ts

And I have these 3 modules & 2 services, AppService service needs the CmtsService:

// # ~/src/app.service.ts
@Provider()
class AppService{
  constructor(private readonly cmtsService: CmtsService)
}
// # ~/src/app.module.ts
@Module({
  imports: [DmaModule],
})
class AppModule{}
// # ~/lib/dma/dma.module.ts
@Module({
  imports: [CmtsModule],
})
class DmaModule{}
// # ~/lib/dma/modules/cmts/cmts.module.ts
@Module({
  imports: [],
  providers: [CmtsService]
})
class CmtsModule{}
// # ~/lib/dma/modules/cmts/cmts.service.ts
@Provider()
class CmtsService{
}

When I run my app, I get this error:

ERROR [ExceptionHandler] Nest can't resolve dependencies of the AppService (?). Please make sure that the argument CmtsService at index [0] is available in the AppModule context.


Solution

  • The solution involved not only to export the service from the nested CmtsModule, but also exporting the CmtsModule itself from the parent module (DmaModule).

    So here's the corrected code that worked:

    (no changes 🔴)

    // # ~/src/app.service.ts
    @Provider()
    class AppService{
      constructor(private readonly cmtsService: CmtsService)
    }
    

    (no changes 🔴)

    // # ~/src/app.module.ts
    @Module({
      imports: [DmaModule],
    })
    class AppModule{}
    

    (yes changes 🟢)

    // # ~/lib/dma/dma.module.ts
    @Module({
      imports: [CmtsModule],
      exports: [CmtsModule], // 👈 Look here
    })
    class DmaModule{}
    

    (yes changes 🟢)

    // # ~/lib/dma/modules/cmts/cmts.module.ts
    @Module({
      imports: [],
      providers: [CmtsService]
      exports: [CmtsService] // 👈 Look here
    })
    class CmtsModule{}
    

    (no changes 🔴)

    // # ~/lib/dma/modules/cmts/cmts.service.ts
    @Provider()
    class CmtsService{
    }