【问题标题】:Why cant nestj resolve dependencies?为什么nestjs不能解析依赖?
【发布时间】:2022-01-15 11:03:32
【问题描述】:

所以我有一个 Nest 应用程序,却被一个感觉很基本的问题困住了。

我需要在 PlaceService 中使用 PlaceVerificationRequestService 但无法正确注入它而不会收到以下错误:

Nest 无法解析 PlaceService 的依赖项(PlaceRepository、ClientService、?)。请确保索引 [2] 处的参数依赖项在 PlaceModule 上下文中可用。

我的方法是遵循与将 ClientService 导入和注入到 PlaceService 时相同的样式/em> 但它仍然不起作用,我不知道为什么。

这是我的代码。

place.module.ts

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [Place, Client, PlaceVerificationRequest],
    }),
  ],
  providers: [PlaceService, ClientService, PlaceVerificationRequestService],
  controllers: [PlaceController],
  exports: [PlaceService],
})

place-verification-request.module.ts

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [PlaceVerificationRequest, Client, Place],
    }),
  ],
  providers: [PlaceVerificationRequestService, ClientService, PlaceService],
  controllers: [PlaceVerificationRequestController],
  exports: [PlaceVerificationRequestService],
})

place.service.ts

@Injectable()
export class PlaceService {
  constructor(
    @InjectRepository(Place)
    private readonly placeRepo: EntityRepository<Place>,
    private readonly clientService: ClientService,
    private readonly reqService: PlaceVerificationRequestService,
  ) {}

感觉就像我错过了一些就在我鼻子前面的东西,因为它感觉非常基本,但我似乎无法发现它。任何有线索的人?谢谢

【问题讨论】:

标签: javascript nestjs mikro-orm


【解决方案1】:

5 小时后好,诀窍是……阅读文档。

Nest can't resolve dependencies of the <provider> (?). Please make sure that the argument <unknown_token> at index [<index>] is available in the <module> context.

Potential solutions:
- If <unknown_token> is a provider, is it part of the current <module>?
- If <unknown_token> is exported from a separate @Module, is that module imported within <module>?
  @Module({
    imports: [ /* the Module containing <unknown_token> */ ]
  })
If the unknown_token above is the string dependency, you might have a circular file import. 

(必须承认他们本可以提出更清晰的错误信息)

所以基本上问题是 PlaceService 被注入 PlaceVerificationRequestService 而 PlaceVerificationRequestService 被注入 PlaceService 所以诀窍是使用forwardRef

PlaceVerificationRequestService

@Inject(forwardRef(() => PlaceService))
private readonly placeService: PlaceService,

地方服务

@Inject(forwardRef(() => PlaceVerificationRequestService))
private readonly reqService: PlaceVerificationRequestService,

【讨论】:

  • 是的,它现在可以工作了.. 老实说,不能感谢这个人,他花了时间和精力与我一起解决这个紧张的错误。所有信誉的人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2015-07-18
相关资源
最近更新 更多