首页 > 解决方案 > 在 NestJs 中,如何根据其接口注入服务?

问题描述

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

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

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

支付服务.ts

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

通知接口.ts

export interface NotificationInterface {
  // some method definitions
}

通知服务.ts

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

问题是我如何注入NotificationService基于NotificationInterface

标签: javascriptnode.jstypescriptecmascript-6nestjs

解决方案


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

付款模块.ts

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

支付服务.ts

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

推荐阅读