问题
NestJS Cannot resolve dependencies of the UsersModule. Error:
Error: Nest can't resolve dependencies of the UsersModule (?). Please verify whether [0] argument is available in the current context.
app.module.ts:
@Module({
imports: [
ConfigModule,
DatabaseModule,
GraphQLModule,
UsersModule,
],
providers: [
ErrorService,
],
exports: [
DatabaseModule,
ErrorService,
],
})
export class AppModule implements NestModule {}
users.module.ts:
@Module({
imports: [
DatabaseModule,
ErrorService,
],
providers: [
UsersService,
...usersProviders,
UserResolver,
],
})
export class UsersModule {
constructor(private readonly errorService: ErrorService) {}
}
Problem is this ErrorService, but for instance Database module is used in similar way, and it works without any error. I'm little confused) Maybe somebody would help. Thank you.
回答1:
ErrorService is not properly injected in UsersModule.
It should either be:
- In the
providersofUsersModule - In the
exportsof one moduleimported byUsersModule
Otherwise, Nest won't be able to resolve it. And adding it to the exports of AppModule doesn't make it globally available, either.
I can see three solutions:
- 1 - Adding
ErrorServiceto theprovidersofUsersModule. But it doesn't look a proper way, as I think/guess that you will reuse this service in many other parts of the code (right?). Thus, better: - 2 - Create a
ErrorsModulewhichexportstheErrorService, thenUsersModulewillimportErrorsModuleand will be able to inject the service.
Like:
// errors.module.ts
@Module({
providers: [ ErrorService ],
exports: [ ErrorService ],
})
export class ErrorsModule {}
// users.module.ts
@Module({
imports: [ErrorsModule],
})
export class UsersModule {
constructor(private readonly errorService: ErrorService) {}
}
- 3 - My favorite, if your service is supposed to be reused (would
LoggerServicebe a better name? If my guess is correct), use a@Globalmodule that you'llimportonly once in your main module (AppModule)
Example:
@Global()
@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {
constructor(private readonly loggerService: LoggerService) { /* initialize logger, or whatever */ }
}
Then you must add LoggerModule to the imports of AppModule, and LoggerService will be injectable anywhere without having to re-declare it.
来源:https://stackoverflow.com/questions/50822301/nestjs-cannot-resolve-dependencies-of-the-usersmodule