NestJS 缺少依赖

Posted

技术标签:

【中文标题】NestJS 缺少依赖【英文标题】:NestJS Missing Dependency 【发布时间】:2021-10-15 11:25:50 【问题描述】:

我遇到了 NestJS 的问题:

"[Nest] 5068 - 08/11/2021, 3:12:02 PM 错误 [ExceptionHandler] Nest 无法解析 AppService (?) 的依赖项。请确保索引 [0] 处的参数 UserRepository在 AppModule 上下文中可用。”

我尝试在导入中添加 AppService,但没有成功。

如何避免这个错误?

app.module.ts:

import  Module  from '@nestjs/common';
import  TypeOrmModule  from '@nestjs/typeorm';
import  AppController  from './app.controller';
import  AppService  from './app.service';
import  User  from './user.entity';

@Module(
  imports: [
    TypeOrmModule.forRoot(
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'password',
      database: 'test',
      entities: [User],
      synchronize: true,
    ),
  ],
  controllers: [AppController],
  providers: [AppService],
)
export class AppModule  

app.controller.ts:

import  Body, Controller, Get, Post  from '@nestjs/common';
import  AppService  from './app.service';
import * as bcrypt from 'bcrypt';

@Controller('api')
export class AppController 
  constructor(private readonly appService: AppService) 
    
  

  @Post('register')
  async register(
    @Body('name') name: string,
    @Body('email') email: string,
    @Body('password') password: string,
    @Body('phone') phone: string,
  ) 
    const hashedPassword = await bcrypt.hash(password, 12);

    return this.appService.create(
      name,
      email,
      password: hashedPassword,
      phone,
    )
  

app.service.ts:

import  Injectable  from '@nestjs/common';
import  InjectRepository  from '@nestjs/typeorm';
import  Repository  from 'typeorm';
import  User  from './user.entity';

@Injectable()
export class AppService 
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>
  ) 
  

  async create(data: any): Promise<User> 
    return this.userRepository.save(data)
  


user.entry.ts:

import  Column, Entity, PrimaryColumn  from "typeorm";

@Entity('users')
export class User 
    @PrimaryColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    email: string;

    @Column()
    phone: string;

    @Column()
    password: string;

谢谢

【问题讨论】:

【参考方案1】:

您需要在您的AppModule 中将TypeormModule.forFeature([User]) 添加到您的imports 以设置您使用的@InjectRepository(User)。使用 TypeORM 模块,forRoot/Async 用于数据库连接和常规 TypeORM 配置,forFeature 用于动态提供程序设置

【讨论】:

以上是关于NestJS 缺少依赖的主要内容,如果未能解决你的问题,请参考以下文章

mysqlwin10缺少依赖

表“令牌”的缺少FROM子句条目

linux 安装 rpm,缺少依赖包,怎么解决

mysql 安装缺少perl依赖怎么解决

React Hook useEffect 缺少依赖项:'list'

@nestjs/mongoose 的文档