【问题标题】:Nest can't resolve dependencies of the Controller (?)Nest 无法解析控制器的依赖关系(?)
【发布时间】:2022-10-24 07:41:54
【问题描述】:

我看到一些问题提到了类似的错误,但没有一个需要这个解决方案。

我开始编写一个 Nest 应用程序,最初在 AppControllerAppService 中编写了我的所有逻辑,现在想将它们移动到单独的模块 CostsModule(以及相关联的 CostsControllerCostsService)中。

我运行了nest g module costsnest g service costs,然后是nest g controller costs,在我尝试将CostsService 注入CostsController 的构造函数之前一切正常。我收到以下错误:

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

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

这对我来说听起来很奇怪,因为我试图注入提供者,它CostsModule 的一部分。它还说参数是Function,这让我认为它可能不是指特定的注入,但如果我注释掉该行,错误就会消失。代码sn-ps:

// src/app.module.ts

@Module({
  imports: [ConfigModule.forRoot(), CostsModule],
})
export class AppModule {}
// src/costs/costs.module.ts

@Module({
  controllers: [CostsController],
  providers: [CostsService],
})
export class CostsModule {}
// src/costs/costs.controller.ts

// ... other imports omitted for brevity, but this one is problematic.
import type { CostsService } from './costs.service';

@Controller('costs')
export class CostsController {
  // If I comment out the line below, the error goes away.
  constructor(private readonly costsService: CostsService) {}

  @Put('fetch')
  updateCosts(
    @Query(
      'ids',
      new ParseArrayPipe({ items: String, separator: ',' })
    )
    ids: string[]
  ): string {
    return this.costsService.updateCosts(ids);
  }
}
// src/costs.service.ts

@Injectable()
export class CostsService {
  updateCosts(ids: string[]): string {
    return ids.join(',');
  }
}

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    此导入由 VS Code 自动添加,但需要将提供程序 (CostsService) 导入文件中(不仅仅是作为类型):

    import type { CostsService } from './costs.service';
    

    将导入更改为以下内容可解决此问题:

    import { CostsService } from './costs.service';
    

    【讨论】:

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