【发布时间】: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