Search code examples
javascriptnode.jstypescriptnestjs

Import nestjs module directly from another module without Importing to AppModule


I am new to nestJs, and I am creating a module called example .module and importing another module called DB.Module, but I am getting the following error if I am not importing DB.Module in App.Module. is it compulsory to import all of module in App.Module

[Nest] 45706  - 07/19/2023, 7:47:55 PM     LOG [NestFactory] Starting Nest application...
[Nest] 45706  - 07/19/2023, 7:47:55 PM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the DbexampleService (?, MysqlService). Please make sure that the argument MongoService at index [0] is available in the AppModule context.

Potential solutions:
- Is AppModule a valid NestJS module?
- If MongoService is a provider, is it part of the current AppModule?
- If MongoService is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing MongoService */ ]
  })

File: example.module.ts

import { Module } from '@nestjs/common';
import { DbexampleService } from './services/dbexample/dbexample.service';
import { HttpExampleService } from './services/http-example/http-example.service';
import { MongoService } from 'src/global/dbModule/services/mongo.service';
import { MysqlService } from 'src/global/dbModule/services/mysql.service';
import { DBModule } from '../global/dbModule/db.module';

@Module({
    imports: [ DBModule],
    providers:[DbexampleService, HttpExampleService, MongoService, MysqlService]
})
export class ExamplesModule {}

File: DB.module.ts

import { Module } from '@nestjs/common';
import { MongoService } from './services/mongo.service';
import { DBController } from './controllers/db.controller';
import { MysqlService } from './services/mysql.service';

@Module({
  controllers: [DBController],
  providers: [MongoService, MysqlService],
  exports:[MongoService, MysqlService]
})
export class DBModule {}

File: App.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { configuration } from '../config/configuration';
import { DbexampleService } from './examples/services/dbexample/dbexample.service';
import { DbexampleController } from './examples/controllers/dbexample/dbexample.controller';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [configuration]
    })
  ],
  controllers: [AppController, DbexampleController],
  providers: [
    AppService,
    DbexampleService
  ],
})
export class AppModule {}

Question: Is it compulsory to import all of module in App.module ?, if no then how can resolve this error ?


Solution

  • Try exporting DBModule in example.module.ts and import ExamplesModule in AppModule.