Careeroza
Shared Modules and Exports
Providers are Private by Default
A provider is visible only inside its own module. To use ProductsService in OrdersService, two things are needed: ProductsModule must export it, and OrdersModule must import ProductsModule.
src/orders/orders.module.ts
import { Module } from '@nestjs/common';
import { ProductsModule } from '../products/products.module';
import { OrdersController } from './orders.controller';
import { OrdersService } from './orders.service';
@Module({
imports: [ProductsModule], // gives access to exported ProductsService
controllers: [OrdersController],
providers: [OrdersService],
})
export class OrdersModule {}The Error You Will See
If you forget the import or the export, the app fails on start with a clear message:
Example
npm run start:devExample output
[Nest] 20112 - ERROR [ExceptionHandler] Nest can't resolve dependencies of the OrdersService (?). Please make sure that the argument ProductsService at index [0] is available in the OrdersModule context. Potential solutions: - Is OrdersModule a valid NestJS module? - If ProductsService is a provider, is it part of the current OrdersModule? - If ProductsService is exported from a separate @Module, is that module imported within OrdersModule?
Note: Modules are singletons: the same ProductsService instance is shared by every module that imports ProductsModule. Do not list ProductsService in the providers of another module, or you get a second, separate instance.