NestJS 缺少依赖项

时间:2021-08-12 04:13:20

标签: node.js backend nestjs

我遇到了 NestJS 的问题:

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

我尝试将 AppService 添加到 imports 中,但没有成功。

如何避免这个错误?

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.entiry.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 个答案:

答案 0 :(得分:1)

你需要在 AppModuleimports 中添加 TypeormModule.forFeature([User]),以启用你使用的 @InjectRepository(User)。TypeORM 模块中,forRoot/Async 是用于数据库连接和通用 TypeORM 配置的,而 forFeature 则用于动态提供程序设置。