我正在尝试使用mongoose并通过跟随nestjs.com的连接来动态配置连接,但是在我的情况下,我需要注入工厂的服务无法解决。
这是AppModule
@Injectable()
class Op implements MongooseOptionsFactory {
constructor(
@Inject(forwardRef(() => EndpointsService))
private endpointsService: EndpointsService) {
}
createMongooseOptions(): MongooseModuleOptions {
return {
uri: this.endpointsService.loginMongoDb
};
}
}
@Module({
imports: [
MongooseModule.forRootAsync({
useClass: Op,
inject: [EndpointsService] // having this doesn't help either
})
],
controllers: [AppController, UserController],
providers: [AppService,
EndpointsService, // is in the core module, but won't be seen
UserService]
})
export class AppModule {
}
非常简单(忽略Op名称,稍后将其移至需要的位置)
这是EndpointsService
@Injectable()
export class EndpointsService {
private readonly _loginApi: string;
private readonly _loginMongoDb: string;
constructor() {
....
但是ap无法启动,出现错误
[Nest] 83842 - 03/20/2020, 10:54:26 AM [NestFactory] Starting Nest application...
[0] [Nest] 83842 - 03/20/2020, 10:54:26 AM [InstanceLoader] MongooseModule dependencies initialized +14ms
[0] [Nest] 83842 - 03/20/2020, 10:54:26 AM [ExceptionHandler] Nest can't resolve dependencies of the Op (?). Please make sure that the argument EndpointsService at index [0] is available in the MongooseCoreModule context.
[0]
[0] Potential solutions:
[0] - If EndpointsService is a provider, is it part of the current MongooseCoreModule?
[0] - If EndpointsService is exported from a separate @Module, is that module imported within MongooseCoreModule?
[0] @Module({
[0] imports: [ /* the Module containing EndpointsService */ ]
[0] })
[0] +0ms
我还尝试在forwardRef
类中使用不带Op
的常规注入,但是结果是相同的。
我想念什么?
答案 0 :(得分:2)
要将服务注入到异步配置中,该服务或提供者必须为
1)通过模块导入在模块范围内 2)通过全局模块提供的全局服务
在这种情况下,EndpointsService
属于AppModule
,但是AppModule
并未导入MongooseModule
进行配置(这很令人困惑,因为主要的循环依赖)。相反,您应该做的是创建一个EndpointsModule
的{{1}}和provides
的{{1}},如下所示:
exports
现在,在您的EndpointsService
中,您可以像这样进行异步配置
@Module({
providers: [EndpointsService],
exports: [EndpointsService],
})
export class EndpointsModule