diu*_*lde 6 javascript dependency-injection node.js 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 {}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在另一个模块的控制器内使用 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 */ ]
})
Run Code Online (Sandbox Code Playgroud)
控制器代码:
@Controller()
export class UserController {
constructor(private readonly userService: UserService) {}
}
Run Code Online (Sandbox Code Playgroud)
控制器模块:
@Module({
imports: [],
providers: [],
controllers: [UserController],
})
export class UserManagementModule {}
Run Code Online (Sandbox Code Playgroud)
主要app.module.ts:
@Module({
imports: [
UserManagementModule,
UserModule,
DataRepositoryModule.forRoot(),
],
controllers: [],
providers: [],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
我很困惑,因为我正在按照错误提示执行操作,将这两个服务添加到提供程序数组(UserModule)中。我可能会错过什么?
从您的错误来看,您的文件导入之间似乎存在循环依赖关系。检查以确保没有循环导入链(即 ServiceA 导入 ServiceB 导入 ServiceA 或 ServiceA 导入 ModuleA 导入 ServiceB 导入 ServiceA)。当在同一模块内使用桶文件时,这种情况尤其常见。
| 归档时间: |
|
| 查看次数: |
10448 次 |
| 最近记录: |