Nest 使用 TypeORM 報錯“Nest can’t resolve dependencies of the BookService…”,如何解決?

Nest 使用 TypeORM 報錯“Nest can’t resolve dependencies of the BookService…”,如何解決?

nest如何使用typeorm

在nest框架中使用typeorm時,常常會遇到報“nest can’t resolve dependencies of the bookservice (?). please make sure that the argument bookentityrepository at index [0] is available in the appmodule context.”的錯。

以下是導致此問題的一些原因和解決方案:

  • 檢查 app.module.ts 中是否錯寫了控制器和提供器的名稱,將其添加到 imports 數組中。
  • 確保 bookentity 模塊已被 appmodule 導入。
  • 檢查 bookentityrepository 是否正確注入到 bookservice 中。

以下是修改后的代碼示例:

app.module.ts

@module({     imports: [typeormmodule.forroot({         type: 'mysql',         host: 'localhost',         port: 3306,         username: 'root',         password: 'root',         database: 'root',         entities: [__dirname + '/**/*.entity.{js,ts}'],         synchronize: true,         timezone: 'z',     }), 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"; import { BookEntity } from './book.entity';  @Injectable() export class BookService {   constructor(     @InjectRepository(BookEntity)     private readonly bookRepository: Repository<BookEntity>,   ) { }    async findAll(): Promise<BookEntity[]> {     return await this.bookRepository.find();   } }

進行上述更改后,報錯應不再出現(xiàn)。如果仍遇到問題,請確保項目中所有依賴項都已正確安裝。

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享