简体   繁体   English

Nest 无法解析 USERRepository 的依赖项

[英]Nest can't resolve dependencies of the USERRepository

This is really an unexpected problem.这真是一个意想不到的问题。

When I type in the terminal "npm run start", there's an error.当我在终端中输入“npm run start”时,出现错误。

[Nest] 40671   - 2018-10-20 17:46:37   [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms
Error: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.
    at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
    at Function.Module.runMain (module.js:703:11)
    at Object.<anonymous> (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
 1: node::Abort() [/usr/local/bin/node]
 2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]
 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/local/bin/node]
 4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]
 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]
 6: 0x909046042fd
Abort trap: 6

I tried everything I can do, but I couldn't solve it.我尝试了我能做的一切,但我无法解决它。 My codes are as below:我的代码如下:

below is [app.module.ts]下面是 [app.module.ts]

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import {TypeOrmModule} from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forRoot(
{
      "type":"postgres",
      "name":"pm_main",
      "host": "localhost",
      "port": 5432,
      "username": "postgres",
      "password": "test",
      "database": "test",
      "synchronize":true
  }
  ),UserModule],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}

Below is [user.service.ts]下面是 [user.service.ts]

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { USER } from './models/user.model';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {

    constructor(
        @InjectRepository(USER)
        private readonly userRepository: Repository<USER>
    ){}

    async findAllUser(): Promise<USER[]> {
        return await this.userRepository.find();
    }
}

Below is [user.module.ts]下面是 [user.module.ts]

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { PROJECT } from 'project/models/project.model';
import { TypeOrmModule } from '@nestjs/typeorm';
import { USER } from './models/user.model';

@Module({
  imports: [TypeOrmModule.forFeature([USER])],
  providers: [UserService],
  controllers: [UserController],
  exports: [UserService]
})
export class UserModule {}

I 100% followed the sample of the document, but it seems not right.我 100% 遵循了文档的示例,但似乎不对。

For more information, the dependencies in package.json are as below:更多信息,package.json 中的依赖项如下:

"dependencies": {
    "@nestjs/common": "^5.3.9" 
    "@nestjs/core": "^5.3.10", 
    "@nestjs/typeorm": "^5.2.0",
    "ajv": "^6.5.4",
    "class-validator": "^0.9.1",
    "fastify-formbody": "^2.0.0",
    "jsonwebtoken": "^8.3.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "pg": "^7.4.3",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^6.0.0",
    "typeorm": "^0.2.7",
    "typescript": "^2.6.2"

Also [user.model.ts] as USER is shown below另外 [user.model.ts] 作为 USER 如下所示

import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from "typeorm";
import { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'
import { user_Gender, user_Status } from "./user.enum";
import { PROJECT } from 'project/models/project.model';

@Entity()
export class USER {
    @PrimaryGeneratedColumn('uuid')
    id:string;

    @Column({unique:true})
    @IsNotEmpty()
    username:string;

    @Column()
    password:string;

    @Column()
    @IsEnum({user_Gender})
    gender:string;

    @Column("jsonb")
    @IsJSON()
    realname?:{
        firstName:string;
        lastName:string;
        middleName:string;
    };

    @Column()
    @IsDate()
    birthday?:Date;

    @CreateDateColumn()
    createAt:Date;

    @UpdateDateColumn()
    updateAt:Date;

    @Column()
    @IsArray()
    industry?:string[];

    @Column()
    @IsEmail()
    email?:string;

    @Column()
    @IsArray()
    org?:string[];

    @Column()
    current_org?:string;

    @Column("jsonb")
    @IsJSON()
    user_location?:{
        country:string;
        province_or_state:string;
        city:string;
        district:string;
        address:string;
    };

    @Column("jsonb")
    @IsJSON()
    mobilephone?:{code:string,number:string};

    @Column("text")
    avater:string;

    @Column()
    @IsArray()
    receive_account?:[{
        name:string,
        number:string,
        bank:string,
        swiftCode?:string,
        address?:string}]

    @Column()
    @IsDate()
    last_loginAt?:Date;

    @Column()
    @IsEnum(user_Status)
    status:string;

    @Column()
    projectsId:[];

    @ManyToMany(type => PROJECT, project => project.members)
    @JoinTable()
    projects:PROJECT[];

}

Problem问题

The problem is that you're assigning a name to your database in the root import:问题是您在根导入中为数据库分配了一个名称:

imports: [TypeOrmModule.forRoot({
      "type":"postgres",
      "name":"pm_main",
      ^^^^^^^^^^^^^^^^^
      "host": "localhost",
      "port": 5432,
      "username": "postgres",
      "password": "test",
      "database": "test",
      "synchronize":true
  }

But then you don't use the same name in the forFeature import:但是随后您不会在forFeature导入中使用相同的名称:

imports: [TypeOrmModule.forFeature([USER])],


Solution解决方案

a) So either add the name to the forFeature import: a) 因此,要么将名称添加到forFeature导入中:

TypeOrmModule.forFeature([USER], 'pm_main')

b) or remove the "name":"pm_main", from your forRoot import. b) 或从您的forRoot导入中删除"name":"pm_main", If you only have one database you can just rely on the implicit default name.如果您只有一个数据库,则可以只依赖隐式默认名称。

Kim's solution doesn't completely solve the problem when there are multiple databases in use.当有多个数据库在使用时,Kim 的解决方案并没有完全解决问题。

finally solve it when check out this issue.最终在检查此问题时解决它。 https://github.com/nestjs/typeorm/issues/105 https://github.com/nestjs/typeorm/issues/105

That is, also need to specify the connection name when @InjectRepositry(Model, connectionName)即@InjectRepositry(Model, connectionName)时也需要指定连接名

Hope this help.希望这有帮助。

import { UserEntity } from './user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
const module = await Test.createTestingModule({
    controllers: [UsersController],
    providers: [UsersService],
    imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line
}).compile();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM