类型错误:无法读取 NestJS 依赖注入上未定义的属性

dic*_*und 2 typescript nestjs

我花了TypeError: Cannot read properties of undefined (reading 'create') at AuthenticationService.register很多时间阅读这个网站(和其他网站),试图找出我错过的内容。可能涉及 Typeorm 的是我知道我比 xe2 x80 x94 任何帮助都表示感谢。

\n

用户.module.ts

\n
import { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n
Run Code Online (Sandbox Code Playgroud)\n

用户.service.ts

\n
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { CreateUserDto } from './dto/create-user.dto';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private usersRepository: Repository<User>,\n  ) {}\n\n  async create(userData: CreateUserDto) {\n    const newUser = await this.usersRepository.create(userData);\n    await this.usersRepository.save(newUser);\n    return newUser;\n  }\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

身份验证.module.ts

\n
import { Module } from '@nestjs/common';\nimport { PassportModule } from '@nestjs/passport';\n\nimport { AuthenticationController } from './authentication.controller';\nimport { AuthenticationService } from './authentication.service';\nimport { UsersModule } from '../users/users.module';\nimport { LocalStrategy } from './local.strategy';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    ConfigModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (configService: ConfigService) => ({\n        secret: configService.get('JWT_SECRET'),\n        signOptions: {\n          expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}`,\n        },\n      }),\n    }),\n  ],\n  providers: [AuthenticationService, LocalStrategy, JwtStrategy],\n  controllers: [AuthenticationController],\n  exports: [AuthenticationService],\n})\nexport class AuthenticationModule {}\n
Run Code Online (Sandbox Code Playgroud)\n

认证.service.ts

\n
import { HttpException, HttpStatus } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport * as bcrypt from 'bcrypt';\nimport { RegisterDto } from './dto/register.dto';\nimport { TokenPayload } from './token-payload.interface';\nimport { PostgresErrorCode } from '../database/postgres-error-codes.enum';\nimport { UsersService } from 'src/users/users.service';\n\nexport class AuthenticationService {\n  constructor(\n    private readonly configService: ConfigService,\n    private readonly jwtService: JwtService,\n    private readonly usersService: UsersService,\n  ) {}\n\n  public async register(registrationData: RegisterDto) {\n    const hashedPassword = await bcrypt.hash(registrationData.password, 10);\n    try {\n      const createdUser = await this.usersService.create({\n        ...registrationData,\n        password: hashedPassword,\n      });\n      createdUser.password = undefined;\n      return createdUser;\n    } catch (error) {\n      if (error?.code === PostgresErrorCode.UniqueViolation) {\n        throw new HttpException(\n          'User with that email already exists',\n          HttpStatus.BAD_REQUEST,\n        );\n      }\n      console.log(`error `, error);\n      throw new HttpException(\n        'Something went wrong',\n        HttpStatus.INTERNAL_SERVER_ERROR,\n      );\n    }\n  } \n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

身份验证.controller.ts

\n
import {\n  Body,\n  Req,\n  Controller,\n  HttpCode,\n  Post,\n  UseGuards,\n  Res,\n  Get,\n} from '@nestjs/common';\nimport { AuthenticationService } from './authentication.service';\nimport { RegisterDto } from './dto/register.dto';\nimport { UsersService } from 'src/users/users.service';\n\n@Controller('authentication')\nexport class AuthenticationController {\n  constructor(\n    private readonly authenticationService: AuthenticationService,\n    private readonly usersService: UsersService,\n  ) {}\n\n @Post('register')\n  async register(@Body() registrationData: RegisterDto) {\n    console.log(`registrationData: `, registrationData);\n    // return this.usersService.create(registrationData); // This works\n    return this.authenticationService.register(registrationData); // This throws error\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

小智 7

添加@Injectable()到您的AuthenticationService班级。