Nest 中 TypeOrm 的正確使用:為什么會(huì)出現(xiàn)“Nest can’t resolve dependencies of the BookService”?

Nest 中 TypeOrm 的正確使用:為什么會(huì)出現(xiàn)“Nest can’t resolve dependencies of the BookService”?

nest 中 typeorm 的正確使用

在使用 nest 時(shí),出現(xiàn)錯(cuò)誤消息“nest can’t resolve dependencies of the bookservice”,提示 bookentityrepository 沒(méi)有在 appmodule 中注冊(cè)。以下是解決方法

代碼示例

app.module.ts:

@module({     imports: [         typeormmodule.forroot({             // 數(shù)據(jù)庫(kù)配置         }),         bookmodule,     ] }) export class appmodule {}

book.module.ts:

@module({   imports: [typeormmodule.forfeature([bookentity])],   controllers: [bookcontroller],   providers: [bookservice],   exports: [bookservice] }) export class bookmodule {}

book.service.ts:

import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm';  export class BookService {     constructor(         @InjectRepository(BookEntity)         private readonly bookRepository: Repository<BookEntity>,     ) {}      // 業(yè)務(wù)邏輯 }

解決方式

  1. 移除 app.module.ts 中冗余的 providers 和 controllers 代碼。
  2. 確保 bookentity 在 typeormmodule.forfeature 中被引用。

如此修改后,nest 便可以正確解析 bookservice 的依賴關(guān)系,消除錯(cuò)誤提示。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊12 分享