为什么Nestjs中导入类的不同方式会影响依赖注入?

问题描述 投票:0回答:1

我正在使用 typescript 开发 NestJS 项目。 我正在尝试将一个类注入到构造函数中,如下所示:

@Injectable()
export class AuthService {
  constructor(
    ...Some omitted content,
    private loginFactory: LoginFactory,
  ) {}
}

LoginFactory是一个工厂类,如下:

@Injectable()
export class LoginFactory {
  constructor(
    private readonly phoneLoginService: PhoneLoginService,
    private readonly verificationCodeLoginService: VerificationCodeLoginService,
  ) {}
}

PhoneLoginService类和VerificationCodeLoginService类都继承了一个名为AbstractLoginService的抽象类,如下:

@Injectable()
export class PhoneLoginService extends AbstractLoginService {
  constructor(protected readonly userService: UserService) {
    super(userService);
  }
}
@Injectable()
export class VerificationCodeLoginService extends AbstractLoginService {
  constructor(protected readonly userService: UserService) {
    super(userService);
  }
}

AbstractLoginService抽象类如下:

export abstract class AbstractLoginService<T extends LoginDto = LoginDto> {
  constructor(protected readonly userService: UserService) {}
  ...Some omitted content
}

我的AuthModule内容如下:

@Module({
  ...Some omitted content
  providers: [
    AuthService,
    PhoneLoginService,
    VerificationCodeLoginService,
    LoginFactory,
  ],
})
export class AuthModule {}

我的代码运行良好,直到我最近清理了文件结构。具体来说,这是我在 AuthService 中导入 LoginFactory 的方式:

import { LoginFactory } from './login-factory.service';
由于上述服务类都在services目录下,所以我添加了一个新文件,名为index.ts,作为统一出口。其内容如下:

export * from './abstract-login.service';
export * from './auth.service';
export * from './login-factory.service';
export * from './phone-login.service';
export * from './verificationCode-login.service';

同时我将AuthService类中LoginFactory类的导入方法改成了如下:

import { LoginFactory } from './';

但是,当我再次启动项目时,却报了以下错误:

Error: Nest can't resolve dependencies of the LoginFactory (?, +). Please make sure that the argument dependency at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If dependency is a provider, is it part of the current AuthModule?
- If dependency is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing dependency */ ]
  })

看起来LoginFactory类的注入有问题。但是当我改变了AuthService类中LoginFactory的导入方式后,一切都恢复正常了。具体来说,我将导入方法改回如下所示:

import { LoginFactory } from './login-factory.service';
我猜这可能是进口订单的问题。但这只是猜测。 我将感谢您的帮助。

我尝试一点一点改变文件的导入方式,最终确定是LoginFactory的导入方式影响了项目的正常运行

node.js typescript nestjs abstract-class
1个回答
0
投票

当您使用桶导入(

./
,或类似
./auth
)时,您不是从相关的index.ts文件中导入
必要的文件,而是从该文件导入所有的导出文件,每个文件也导入它需要的所有内容。在这种情况下,您将在文件本身上创建循环导入语句。
auth.service
./
导入,这意味着它导入
auth.service
abstract-ogin.service
login-factory.service
等。事实上
auth.service
导入
auth.service
已经是一个危险信号,但是如果你查看
login-factory.service
并且它 also
./
导入,那么它 also 导入
auth.service
现在你有两个部分循环链,并且可以继续处理尽可能多的文件。

我的桶文件的一般规则是,从功能的外部,可以从它们导入,但是从功能的内部,直接从文件导入。这也有助于区分该功能的公共 API 和私有 API。

© www.soinside.com 2019 - 2024. All rights reserved.