到目前为止,我有一个应用程序可以接收服务作为对控制器的依赖关系,但是我想找到一种方法,而不是声明该服务的具体实现,以便能够“向”该服务实现的接口的控制器,以与该服务的具体实现分离。在Nest js中如何完成?
答案 0 :(得分:1)
为此,您必须为接口创建一个注入令牌,并在注入服务时将@Inject()
装饰器与注入令牌一起使用。然后,您可以在模块中声明要为该注入令牌提供的实现。
下面是一个简单的问候服务界面和我们的注入令牌,将我们的服务注册为提供者时将使用
。// This will be our injection token.
export const GREETING_SERVICE = 'GREETING SERVICE';
export interface IGreetingService {
greet(name: string): Promise<string>;
}
将实现问候语界面的基本服务...
import { Injectable } from '@nestjs/common';
import { IGreetingService } from './greeting-service.interface';
@Injectable()
export class ProfessionalGreetingService implements IGreetingService {
public async greet(name: string): Promise<string> {
return `Hello ${name}, how are you today?`;
}
}
还有我们的问候语模块,我们在其中使用令牌注册服务...
import { Module } from '@nestjs/common';
import { ProfessionalGreetingService } from './services/professional-greeting.service';
import { GREETING_SERVICE } from './services/greeting-service.interface';
import { GreetingController } from './controllers/greeting.controller';
@Module({
providers: [
{
// You can switch useClass to different implementation
useClass: ProfessionalGreetingService,
provide: GREETING_SERVICE
}
],
controllers: [
GreetingController
]
})
export class GreetingModule {}
现在,当我们注入服务时,可以将@Inject()
装饰器与注入令牌一起使用。您注入useClass
中GreetingModule
的任何实现都将被注入...
import { Controller, Get, Inject, Query } from '@nestjs/common';
import { GREETING_SERVICE, IGreetingService } from '../services/greeting-service.interface';
@Controller('greeting')
export class GreetingController {
constructor(
@Inject(GREETING_SERVICE)
private readonly _greetingService: IGreetingService
) {}
@Get()
public async getGreeting(@Query('name') name: string): Promise<string> {
return await this._greetingService.greet(name || 'John');
}
}
https://github.com/jmw5598/nestjs-di-decoupling-with-interfaces https://docs.nestjs.com/fundamentals/custom-providers