NestJS无法解决依赖关系

时间:2020-03-01 19:17:22

标签: node.js typescript nestjs

运行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会引发此错误?

1 个答案:

答案 0 :(得分:1)

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

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

2)将private logger = new Logger('Account Service')移动到第三位置并将其标记为@Optional(),以便在值未知时Nest不会抛出错误。

3)将Logger添加到providers的{​​{1}}数组中,然后使用AccountModule方法正确设置上下文

内置的Logger类为this.logger.setContext(),因此可以通过DI使用它,但是您必须确保提供的内容与NestJS生态系统中的任何其他提供程序一样。