在NestJs中,如何基于服务接口注入服务?

时间:2019-12-23 07:31:41

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

我有下一个模块: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
}

问题是如何基于NotificationService注入NotificationInterface

1 个答案:

答案 0 :(得分: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,
}