gpt4 book ai didi

javascript - 在 NestJs 中,如何根据其接口(interface)注入(inject)服务?

转载 作者:行者123 更新时间:2023-12-04 14:45:36 28 4
gpt4 key购买 nike

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

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

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

支付服务.ts
export class PaymentService {
constructor(private readonly notificationService: NotificationInterface,
}

通知接口(interface).ts
export interface NotificationInterface {
// some method definitions
}

通知服务.ts
@Injectable()
export class NotificationService implements NotificationInterface {
// some implemented methods
}

问题是如何注入(inject) NotificationService基于 NotificationInterface ?

最佳答案

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

付款模块.ts

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

支付服务.ts
export class PaymentService {
constructor(@Inject('NotificationInterface') private readonly notificationService: NotificationInterface,
}

关于javascript - 在 NestJs 中,如何根据其接口(interface)注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451585/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com