【问题标题】:NestJS Missing DependencyNestJS 缺少依赖
【发布时间】: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;
}

谢谢

【问题讨论】:

    标签: node.js backend nestjs


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2017-12-25
      • 2015-04-18
      • 2020-03-24
      • 2021-04-26
      • 2012-07-12
      • 1970-01-01
      相关资源
      最近更新 更多