I'm trying to use a service from a services module in the main scaffolded app controller in NestJS.
This is working - helloWorldsService.message displays the expected greeting in the @Get method - but the imports of HelloWorldsService in app.module and app.controller seem redundant, and seems to violate encapsulation of the services by the services module.
Do I have this right, is this how you consume a discreet service from a different module, or am I missing something? The reason I ask is: if this is correct, and you have to directly reference the other classes (e.g. reference HelloWorldService directly in the controller), then I have trouble seeing why one bothers with the providers/imports properties of the @Module declaration.
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 {}