我有四个模块,分别是App-> Dog-> Access-> Mongo(依赖关系如箭头所示)。
在应用程序中,MongoDB也与MongooseModule.forRootAsync()
连接,然后在MongoModule
和MongooseModule.forFeature()
中使用。
完整的代码可以在此example project中找到。
我想使用通过AccessGuard
提供的AccessModule
(内部使用MongoModule
)在DogModule
中可用。
使用下面的代码,我收到此错误消息:
[Nest] 31164 - 11/10/2020, 5:11:29 PM [ExceptionHandler] Nest can't resolve dependencies of the AccessGuard (?). Please make sure that the argument Mongo at index [0] is available in the DogModule context.
Potential solutions:
- If Mongo is a provider, is it part of the current DogModule?
- If Mongo is exported from a separate @Module, is that module imported within DogModule?
@Module({
imports: [ /* the Module containing Mongo */ ]
})
app.module.ts:
@Module({
imports: [
MongooseModule.forRootAsync({
useFactory: async () => {
let info = mongod.getInstanceInfo()
if (!info) {
await mongod.start()
}
info = mongod.getInstanceInfo()
if (info) {
return {
uri: info.uri,
dbName: "dogsDB",
useCreateIndex: true,
promiseLibrary: global.Promise,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
} as MongooseModuleOptions
}
},
}),
DogModule,
],
})
export class AppModule {}
dog.module.ts:
@Module({
imports: [AccessModule],
providers: [AccessGuard],
controllers: [DogController],
})
export class DogModule {}
access.module.ts:
@Module({
imports: [MongoModule],
providers: [AccessGuard],
exports: [AccessGuard],
})
export class AccessModule {}
access.guard.ts:
@Injectable()
export class AccessGuard implements CanActivate {
constructor(private mongo: Mongo) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
return await this.mongo.hasDog()
}
}
mongo.module.ts
@Module({
imports: [
MongooseModule.forFeature([
{
name: Dog.name,
schema: DogSchema,
},
]),
],
providers: [Mongo],
exports: [Mongo],
})
export class MongoModule {}
当我将MongoModule
添加到DogModule
时,它将起作用。
但是,我不应该这样,因为DogModule实际上并不使用Mongo
类。
DogModule
仅需要AccessGuard
中的AccessModule
。
答案 0 :(得分:1)
快速说明:不需要将防护罩和其他增强器添加到private static JsonObject execPostRequestTest(URL url, String jsonString) {
StringEntity stringEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url.toString());
request.setEntity(stringEntity);
try {
HttpResponse httpResponse = httpClient.execute(request);
String responseString = new BasicResponseHandler().handleResponse(httpResponse);
return new JsonParser().parse(responseString).getAsJsonObject();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
数组中。它们是providers
,但它们生活在伪空间中,该空间允许它们位于@Injectable()
的{{1}}数组之外。我知道很奇怪,但这就是事实。
从那里发生的所有需求都是,如果在模块中使用了防护,则该模块需要访问防护依赖,在这种情况下,模块需要将providers
设为{{1 }} @Module()
imports: [MongoModule]
类MongoModule
和provides