Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS.
Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't help but notice that the imports of HelloWorldsService in both app.module and app.controller appear redundant. This seems to go against the encapsulation concept of the services by the services module.
Am I approaching this correctly? Is this the proper way to consume a discrete service from a different module, or is there something that I'm overlooking? My confusion stems from the fact that if this approach is correct, where we have to directly reference other classes (such as referencing HelloWorldService directly in the controller), then the purpose of the providers/imports properties in the @Module declaration becomes unclear.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RouterModule } from './router/router.module';
import { ServicesModule } from './services/services.module'; //<-- import service MODULE
import { EventsModule } from './events/events.module';
import { HelloWorldsService } from './services/hello-worlds/hello-worlds.service'; //<-- import service module SERVICE
@Module({
imports: [RouterModule, ServicesModule, EventsModule],
controllers: [AppController],
providers: [AppService, HelloWorldsService],
})
export class AppModule {}
//Controller code:
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { HelloWorldsService } from './services/hello-worlds/hello-worlds.service'; //<-- importing service again in consuming controller
@Controller()
export class AppController {
constructor(private readonly appService: AppService, private readonly helloWorldsService: HelloWorldsService ) {}
@Get()
getHello(): string {
return this.helloWorldsService.Message();
}
}
//services.module
import { Module } from '@nestjs/common';
import { WagerAccountService } from './wager-account/wager-account.service';
import { WagerAccountHttpService } from './wager-account.http/wager-account.http.service';
import { CustomerIdentityHttpService } from './customer-identity.http/customer-identity.http.service';
import { HelloWorldsService } from './hello-worlds/hello-worlds.service';
@Module({
exports:[HelloWorldsService],
providers: [CustomerIdentityHttpService, WagerAccountService, WagerAccountHttpService, CustomerIdentityHttpService, HelloWorldsService]
})
export class ServicesModule {}