【问题标题】:Nest can't resolve dependencies of the WithdrawServiceNest 无法解析 WithdrawService 的依赖关系
【发布时间】:2021-04-28 00:52:04
【问题描述】:

应用程序的架构非常简单,主应用程序有两个控制器。

  • 应用(主要服务)
  • 存款(控制器 + 服务)
  • 撤销(控制器+服务)

在某些情况下,存款服务必须运行提款服务的功能,因此它会初始化提款服务。在我添加 MongoDB 部分之前,一切都非常顺利。

当我将构造函数添加到提取服务时它开始失败:

@Injectable()
export class WithdrawService {
    constructor(@InjectModel('withdraw') private withdrawModel: Model<WithdrawDocument>){}

Withdraw.module.ts:

import { Module } from '@nestjs/common';
import { WithdrawController } from './withdraw.controller';
import { WithdrawService } from './withdraw.service';
import { MongooseModule } from '@nestjs/mongoose';
import { WithdrawSchema } from './dto/withdraw.dto';


@Module({
  imports: [MongooseModule.forFeature([{ name: 'withdraws', schema: WithdrawSchema }])],
  controllers: [WithdrawController],
  providers: [WithdrawService, ],
  exports: [WithdrawService]
})
export class WithdrawModule {}

deposits.module.ts:

import { Module } from '@nestjs/common';
import { DepositsController } from './deposits.controller';
import { DepositsService } from './deposits.service';
import { UtilsModule } from '../utils/utils.module';
import { WithdrawModule } from '../withdraw/withdraw.module';
import { DepositSchema } from './dto/deposit-dto';
import { MongooseModule } from '@nestjs/mongoose';
import { WithdrawSchema } from '../withdraw/dto/withdraw.dto';

@Module({
  imports: [UtilsModule, WithdrawModule, MongooseModule.forFeature([{ name: 'deposits', schema: DepositSchema }])],
  controllers: [DepositsController],
  providers: [DepositsService]
})
export class DepositsModule {}

deposit.service.ts:

@Injectable()
export class DepositsService {

    constructor(private withdrawService: WithdrawService,

...

问题是当 DepositsService 试图初始化 WithdrawService 时,有什么线索可以解决吗?

错误:

Nest can't resolve dependencies of the WithdrawService (?). Please make sure that the argument withdrawModel at index [0] is available in the WithdrawModule context.

Potential solutions:
- If withdrawModel is a provider, is it part of the current WithdrawModule?
- If withdrawModel is exported from a separate @Module, is that module imported within WithdrawModule?
  @Module({
    imports: [ /* the Module containing withdrawModel */ ]
  })

在将构造函数添加到 WithdrawService 和 mongoDB 部分之前,这两个服务可以通信

【问题讨论】:

    标签: node.js mongodb typescript mongoose nestjs


    【解决方案1】:

    在您的WithdrawModule 中,您使用的是MongooseModule.forFeature([{ name: 'withdraws', schema: WithdrawShcema }]),但在您的WithdrawService 中,您使用的是@InjectModel('withdraw')。在后台,forFeature 创建注入令牌withdrawsModel@InjectModel() 将注入令牌的元数据设置为withdrawModel。这些令牌不匹配,因此 Nest 无法确定注入什么。您要么需要将MongooseModule 更改为使用withdraw(单数),要么需要将@InjectModel() 更改为使用withdraws(复数)

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2018-11-21
      • 2020-03-12
      • 2020-07-03
      • 2020-03-07
      • 2019-12-15
      • 2020-12-14
      • 2020-12-13
      • 2019-12-09
      相关资源
      最近更新 更多