【发布时间】:2021-04-01 15:37:45
【问题描述】:
我正在尝试在 NestJS 的主脚手架应用控制器中使用服务模块中的服务。
这是有效的 - helloWorldsService.message 在 @Get 方法中显示预期的问候 - 但是 app.module 和 app.controller 中 HelloWorldsService 的导入似乎是多余的,并且似乎违反了服务模块对服务的封装。
我是否有这个权利,这是您使用来自不同模块的谨慎服务的方式,还是我遗漏了什么?我问的原因是:如果这是正确的,并且您必须直接引用其他类(例如,直接在控制器中引用 HelloWorldService),那么我很难理解为什么要打扰 @Module 声明的提供程序/导入属性。
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 {}
【问题讨论】:
标签: javascript typescript nestjs