javascript - 当它们属于同一个模块时,如何将 nestjs 服务注入(inject)另一个服务?

标签 javascript node.js dependency-injection nestjs

我在 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 {}
但是,当我尝试在另一个模块的 Controller 中使用 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 代码:
@Controller()
export class UserController {
  constructor(private readonly userService: UserService) {}
}
Controller 模块:
@Module({
  imports: [],
  providers: [],
  controllers: [UserController],
})
export class UserManagementModule {}
主 app.module.ts:
@Module({
  imports: [
    UserManagementModule,
    UserModule,
    DataRepositoryModule.forRoot(),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
我很困惑,因为我正在按照错误提示的那样做,在提供者数组 (UserModule) 中添加这两个服务。我可能会错过什么?

最佳答案

从您的错误来看,您的文件导入之间似乎存在循环依赖关系。检查以确保您没有循环导入链(即 ServiceA 导入 ServiceB 导入 ServiceA 或 ServiceA 导入 ModuleA 导入 ServiceB 导入 ServiceA)。在同一模块内使用桶文件时,这尤其会变得普遍。

关于javascript - 当它们属于同一个模块时,如何将 nestjs 服务注入(inject)另一个服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167307/

相关文章:

c# - Ninject:单例绑定(bind)语法?

javascript - 引用错误 : documentFragmentChildren is not defined

javascript - native react : How to stop child component rerendering on state change?

node.js - process.on ('SIGINT' 多个终止信号

node.js - JWT 撤销信息存放在哪里,mongoDB 还是 Redis?

javascript - 从使用 Express 的 Node JS 服务器导出一个变量,以便我可以在客户端访问它?

Spring 未将 bean 注入(inject)线程

Javascript 从索引处的数组获取值,同时如果索引不存在则避免未定义?

javascript - 如何在 JavaScript 中匹配一系列字符的正则表达式中添加反引号?

dependency-injection - 缺少方法异常 : No parameterless constructor defined for type