【问题标题】:How to inject a nestjs service into another service when both belong to the same module?当两个服务都属于同一个模块时,如何将一个nestjs服务注入另一个服务?
【发布时间】:2021-05-15 22:27:54
【问题描述】:

我在 NestJS 中有以下场景:

// user.service.ts
@Injectable()
export class UserService {
  constructor(
    private readonly userRepository: UserRepository,
    private readonly userProfileService: UserProfileService,
  ) {}
}


// user-profile.service.ts
@Injectable()
export class UserProfileService {
  constructor(
    private readonly userProfileRepository: UserProfileRepository,
  ) {}
}


// user.module.ts
@Module({
imports: [DataRepositoryModule], // Required for the repository dependencies
  providers: [UserService, UserProfileService],
  exports: [UserService, UserProfileService],
})
export class UserModule {}

但是,当我尝试在另一个模块的控制器中使用 UserService 时,我收到以下错误:

Nest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument dependency at index [1] is available in the UserModule context.
Potential solutions:    
- If dependency is a provider, is it part of the current UserModule?
- If dependency is exported from a separate @Module, is that module imported within UserModule?
@Module({
        imports: [ /* the Module containing dependency */ ]
      })

控制器代码:

@Controller()
export class UserController {
  constructor(private readonly userService: UserService) {}
}

控制器模块:

@Module({
  imports: [],
  providers: [],
  controllers: [UserController],
})
export class UserManagementModule {}

主app.module.ts:

@Module({
  imports: [
    UserManagementModule,
    UserModule,
    DataRepositoryModule.forRoot(),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

我很困惑,因为我完全按照错误的建议做,将这两个服务都添加到提供程序数组 (UserModule) 中。我可能会错过什么?

【问题讨论】:

    标签: javascript node.js dependency-injection nestjs


    【解决方案1】:

    根据您的错误,您的文件导入之间似乎存在循环依赖关系。检查以确保您没有进行循环导入链(即 ServiceA 导入 ServiceB 导入 ServiceA 或 ServiceA 导入 ModuleA 导入 ServiceB 导入 ServiceA)。在同一模块中使用桶文件时,这种情况尤其普遍。

    【讨论】:

    • 谢谢,在这种情况下,通过删除任何提供商的桶文件解决了问题。 NestJS 官方文档中有一条警告,他们不建议以这种方式使用它们:docs.nestjs.com/fundamentals/circular-dependency 我认为错误消息具有误导性,它让我浪费了很多时间。
    • 循环依赖有两种类型。循环文件导入(文件 A 导入文件 B 导入文件 A)。 Nest 无法轻易检测到这些,因为令牌可以以 undefined 的形式出现,因此 Nest 将其称为 dependency。另一种是注入依赖(服务A注入服务B注入服务A)。这些 Nest 可以检测并给出文档中显示的错误(大部分时间)
    猜你喜欢
    • 2019-01-20
    • 2013-12-22
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多