问题描述
我正在尝试创建一个超级简单的 cron 任务
@Injectable()
export class CronService {
constructor(
@Inject(forwardRef(() => PurchaseService))
private purchaseService: PurchaseService) {}
@Cron('45 * * * * *')
handleCron() {
this.purchaseService.handleOldPurchases();
}
}
当我在 imports
部分的模块中定义服务时,它仅在我删除购买服务注入时运行,如果我将其添加到 providers
部分 - 它根本不会运行生产:(
@Module({
imports: [
CronService,],
运行 cron - 但抛出 nest can't resolve dependencies of the CronService (?). Please make sure that the argument PurchaseService at index [0] is available in the CronService context.
@Module({
providers: [
CronService,
根本不运行
解决方法
假设您的 PurchaseService
与 CronService
在同一个模块中
采购服务:
@Injectable()
export class PurchaseService {
handleOldPurchases() {}
}
CronService:
@Injectable()
export class CronService {
constructor(private _purchaseService: PurchaseService) {}
@Cron('45 * * * * *')
handleCron() {
this._purchaseService.handleOldPurchases();
}
}
Cron 模块:
@Module({
providers: [CronService,PurchaseService]
})
export class CronModule {}
如果您的 CronService
和 PurchaseService
在不同的模块中,则包含 PurchaseService
的模块必须提供和导出 PurchaseService
,而使用 {{1} } 必须导入 PurchaseService
购买模块:
PurchaseModule
Cron 模块:
@Module({
providers: [PurchaseService],// this tells the interpreter this module offers PurchaseService
exports: [PurchaseService] // this tells the interpreter for those modules that import PurchaseModule can have access to PurchaseService
})
export class PurchaseModule {}
最后,当且仅当服务相互依赖时才使用forwardRef(),即服务A消耗服务B的methodB(),而服务B也消耗服务A的methodA。恕我直言,你应该尽量避免这种耦合。
如果您需要更多帮助,NestJS 不和谐:https://discord.com/invite/nestjs