繁体   English   中英

NestJs中,如何根据接口注入服务?

[英]In NestJs, how to inject a service based on its interface?

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

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

在下一个服务中,我想访问基于接口的服务

支付服务.ts

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

通知.interface.ts

export interface NotificationInterface {
  // some method definitions
}

通知.service.ts

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

问题是如何基于NotificationInterface NotificationService

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

支付模块.ts

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

支付服务.ts

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

正如 Gabriel 所提到的,您不能使用接口,因为它们在运行时不存在,但您可以使用抽象 class 它们在运行时可用,因此它们可以用作您的依赖注入令牌。

在 Typescript、class 声明中也创建类型,所以你也可以实现它们,你不必扩展它们。

按照您的示例,您可以执行以下操作:

通知.interface.ts

export abstract class NotificationInterface {
  abstract send(): Promise<void>;
  // ... other method definitions
}

通知.service.ts

export class NotificationService implements NotificationInterface {
  async send() {...}
} 

然后在你的模块中,像这样提供它:

import NotificationInterface from "..."
import NotificationService from "..."

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

最后,通过 payments.service.ts 中的接口使用注入的服务

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

现在您不需要提供任何与您的 class 实现(并且只是一个 DI 构造)有些“无关”的自定义标记(如字符串或符号),但您可以使用 OOP model 中的结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM