【问题标题】:NestJS Unable to Resolve DependenciesNestJS 无法解决依赖关系
【发布时间】:2020-06-14 03:48:37
【问题描述】:

我在运行 NestJS 应用程序时遇到此错误。

[Nest] 19139   - 03/01/2020, 2:10:01 PM   [ExceptionHandler] Nest can't resolve dependencies of the AccountsService (AccountRepository, ?, HashPasswordService). Please make sure that the argument Object at index [1] is available in the AccountsModule context.

Potential solutions:
- If Object is a provider, is it part of the current AccountsModule?
- If Object is exported from a separate @Module, is that module imported within AccountsModule?
  @Module({
    imports: [ /* the Module containing Object */ ]
  })
 +1ms

我有点困惑是什么原因造成的。据我所知,我的代码看起来是正确的。这是我的 AccountsService 类的定义:

import { Injectable, ConflictException, Logger, InternalServerErrorException, NotFoundException, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Account } from 'src/accounts/entities/account';
import { Repository, FindManyOptions, UpdateDateColumn } from 'typeorm';
import { CreateAccount } from 'src/accounts/dtos/create-account';
import { GetAccountsWithFilters } from 'src/accounts/dtos/get-accounts-with-filters';
import { UpdateAccountProfileInfo } from 'src/accounts/dtos/update-account-profile-info';
import { HashPasswordService } from '../hash-password/hash-password.service';
import { UpdateEmail } from 'src/accounts/dtos/update-email';
import { UpdatePhone } from 'src/accounts/dtos/update-phone';
import { AccountRepository } from 'src/accounts/repositories/account-repository';


/**
 * AccountsService encapsulates all the actions that can be performed by an account.
 */
@Injectable()
export class AccountsService {

    constructor(
        @InjectRepository(AccountRepository) private accountRepository: AccountRepository,
        private logger = new Logger("Accounts Service"),

        @Inject(HashPasswordService)
        private hashPasswordService: HashPasswordService,
    ) { }
    // more code here
}

我的模块看起来像这样。

import { Module } from '@nestjs/common';
import { AccountsService } from './services/accounts/accounts.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Account } from './entities/account';
import { AccountsController } from './controllers/accounts/accounts.controller';
import { AccountCleanerService } from './services/account-cleaner/account-cleaner.service';
import { AuthenticationService } from './services/authentication/authentication.service';
import { AuthenticationController } from './controllers/authentication/authentication.controller';
import { HashPasswordService } from './services/hash-password/hash-password.service';
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { JwtStrategy } from './auth-strategies/jwt-strategy';
import { AccountRepository } from './repositories/account-repository';

@Module({
  imports: [
    TypeOrmModule.forFeature([
      Account,
      AccountRepository,
    ]),
    JwtModule.register({
      secret: "SOME_APP_SECRET",
      signOptions: {
        expiresIn: 3600
      }
    }),
    PassportModule.register({
      defaultStrategy: "jwt",
    }),
  ],
  controllers: [
    AccountsController, 
    AuthenticationController,
  ],
  providers: [
    AccountRepository,
    HashPasswordService,
    AccountsService, 
    AccountCleanerService, 
    AuthenticationService,  
    JwtStrategy,
  ],
  exports: [JwtStrategy, PassportModule],
})
export class AccountsModule { }

最后,这里是应用模块:

import { Module } from '@nestjs/common';
import { AccountsModule } from './accounts/accounts.module';
import { TypeOrmModule } from "@nestjs/typeorm";
import {Account} from "./accounts/entities/account";
import { ConfigModule } from "@nestjs/config";
import account from "./../config/account";
import auth from "./../config/auth";
import database from "./../config/database";
import server from "./../config/server";
import { AccountRepository } from './accounts/repositories/account-repository';

@Module({
  imports: [
    AccountsModule,
    ConfigModule.forRoot({
      // make this module available globally
      isGlobal: true,

      // The configuration files.
      load: [
        account,
        auth,
        database,
        server
      ],
    }),
    TypeOrmModule.forRoot({
      type: "mongodb",
      url: "my connection string here",
      entities: []
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule { }

如您所见,我已经清楚地为模块提供了服务。所以,我有点困惑为什么 Nest 无法解决依赖关系。此外,除了上面提供的 App 模块之外,现在不应该有任何其他模块。任何想法为什么 NestJS 会抛出这个错误?

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    Nest 无法解决 Logger 的依赖关系,并且由于 providers 数组中没有提供它,因此无法解决它。您有三个选择:

    1) 将private logger = new Logger('Account Service') 移动到构造函数的主体中

    2) 将private logger = new Logger('Account Service')移动到第三个位置,标记为@Optional(),这样Nest在值未知的时候不会报错。

    3) 将Logger 添加到AccountModuleproviders 数组中,然后使用this.logger.setContext() 方法正确设置上下文

    内置的 Logger 类是@Injectable(),因此可以通过 DI 使用它,但您必须确保它像 NestJS 生态系统中的任何其他提供者一样提供。

    【讨论】:

    • 哦。我的错。哈哈。感谢您的帮助:)
    猜你喜欢
    • 2019-09-12
    • 2020-05-31
    • 1970-01-01
    • 2018-09-01
    • 2016-02-16
    • 2017-02-20
    相关资源
    最近更新 更多