如何在Nestjs的控制器的构造函数中注入服务的接口?

时间:2020-09-28 14:27:55

标签: nestjs

到目前为止,我有一个应用程序可以接收服务作为对控制器的依赖关系,但是我想找到一种方法,而不是声明该服务的具体实现,以便能够“向”该服务实现的接口的控制器,以与该服务的具体实现分离。在Nest js中如何完成?

1 个答案:

答案 0 :(得分:1)

为此,您必须为接口创建一个注入令牌,并在注入服务时将@Inject()装饰器与注入令牌一起使用。然后,您可以在模块中声明要为该注入令牌提供的实现。

下面是一个简单的问候服务界面和我们的注入令牌,将我们的服务注册为提供者时将使用

greeting-service.interface.ts

// This will be our injection token.
export const GREETING_SERVICE = 'GREETING SERVICE';

export interface IGreetingService {
  greet(name: string): Promise<string>;
}

将实现问候语界面的基本服务...

professional-greeting.service.ts

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?`;
  }
}

还有我们的问候语模块,我们在其中使用令牌注册服务...

greeting.module.ts

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()装饰器与注入令牌一起使用。您注入useClassGreetingModule的任何实现都将被注入...

greeting.controller.ts

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://jasonwhite.xyz/posts/2020/10/20/nestjs-dependency-injection-decoupling-services-with-interfaces/

https://github.com/jmw5598/nestjs-di-decoupling-with-interfaces https://docs.nestjs.com/fundamentals/custom-providers