【问题标题】:In NestJs, how to inject a service based on its interface?在 NestJs 中,如何根据其接口注入服务?
【发布时间】:2019-12-23 07:31:41
【问题描述】:

我有下一个模块:payment.module.ts

@Module({
  controllers: [PaymentController],
})
export class PaymentModule {}

在下一个服务中,我希望能够访问基于接口的服务

payment.service.ts

export class PaymentService {
   constructor(private readonly notificationService: NotificationInterface,
}

notification.interface.ts

export interface NotificationInterface {
  // some method definitions
}

notification.service.ts

@Injectable()
export class NotificationService implements NotificationInterface {
  // some implemented methods
}

问题是如何基于NotificationInterface注入NotificationService

【问题讨论】:

    标签: javascript node.js typescript ecmascript-6 nestjs


    【解决方案1】:

    这是我找到的解决方案...使用接口作为值类型是不可能的,因为它们只存在于开发过程中。转译后接口不再存在,导致空对象值。尽管使用字符串键作为提供值和注入装饰器,但您的问题有一个解决方案:

    payment.module.ts

    @Module({
      providers: [
        {
          provide: 'NotificationInterface',
          useClass: NotificationService
        }
      ]
    })
    export class PaymentModule {}
    

    payment.service.ts

    export class PaymentService {
       constructor(@Inject('NotificationInterface') private readonly notificationService: NotificationInterface,
    }
    

    【讨论】:

    • 好答案,这是我使用的方法,也是解决此问题的推荐 NestJS
    • 这个实现有一个不错的博客。 jasonwhite.xyz/posts/2020/10/20/…
    • @BurcuGeneci 你能建议如何在单元测试中解决这些依赖。我在阅读您提到的博客后进行了类似的更改,我收到了这个错误:Nest could not find MyService element (this provider does not exist in the current context)
    • @Gabriel 你能告诉我在编写单元测试时如何添加这些依赖项吗?
    • 感谢您的示例,帮助我弄清楚如何解决我的注射丛林问题 :)
    猜你喜欢
    • 1970-01-01
    • 2020-08-06
    • 2020-09-09
    • 2018-11-16
    • 2020-06-23
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多