javascript - 在 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
?
解决方案
这是我找到的解决方案......使用接口作为值类型是不可能的,因为它们只存在于开发过程中。转译后接口不再存在,导致空对象值。尽管使用字符串键作为提供值和注入装饰器,但您的问题有一个解决方案:
付款模块.ts
@Module({
providers: [
{
provide: 'NotificationInterface',
useClass: NotificationService
}
]
})
export class PaymentModule {}
支付服务.ts
export class PaymentService {
constructor(@Inject('NotificationInterface') private readonly notificationService: NotificationInterface,
}
推荐阅读
- c++ - 禁用定时器时出现硬故障?
- unit-testing - 如何对 registry.gitlab.com 中的镜像进行单元测试和部署到自托管 microk8s
- java - Firebase 管理员 - Gradle - Fat Jar - 无法正常工作
- python - 合理的项目结构
- android - 传递数据总是返回 0
- c# - 如何在 Rx.NET 中组合两个不同的 GroupedStreams?
- sql-server - IN() 中子查询的 csv 导致转换错误
- javascript - HTML CSS - 单击时使图标更改颜色(如链接)
- arrays - 在 React 中构建可链接的过滤器组件?
- android - 上下文发送广播在真实设备中不起作用