I am new to nest js and I am trying to implement authenticating with nest js using JWT Token. I flow This article to implement my authenticating code.
When I run the code I get an error like this.
**
[Nest] 16236 - 01/29/2022, 7:16:06 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthenticationService (?, JwtService, ConfigService). Please make sure that the argument UsersService at index [0] is available in the AuthenticationModule context. Potential solutions:
- If UsersService is a provider, is it part of the current AuthenticationModule?
- If UsersService is exported from a separate @Module, is that module imported within AuthenticationModule? @Module({ imports: [ /* the Module containing UsersService */ ] })
**
And I have no idea what is wrong with my code.
This is my UserModule :
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}
This is my AuthenticationModule:
@Module({
imports: [
UsersModule,
PassportModule,
ConfigModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,
},
}),
}),
],
controllers: [AuthenticationController],
providers: [AuthenticationService, LocalStrategy, JwtStrategy],
})
export class AuthenticationModule {}
This is my AppModule:
@Module({
imports: [
TypeOrmModule.forRoot(ORM_CONFIG),
ConfigModule.forRoot({
validationSchema: Joi.object({
JWT_SECRET: 'ABC',
JWT_EXPIRATION_TIME: '1d',
}),
}),
ItemModule,
CategoryModule,
ItemHasCategoryModule,
OrderModule,
OrderHasItemModule,
PaymentModule,
CustomerModule,
UsersModule,
AuthenticationModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
My AuthenticationService File :
@Injectable()
export class AuthenticationService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
My UsersService File :
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User) private readonly userRepository: Repository<User>,
) {}
If anyone knows the answer to this...I really need your help..I am struggling with this error for hours...Thank you.
CodePudding user response:
You need to export UserService to be able to use it in other modules.
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService]
})
export class UsersModule {}
Explanation on exports array:
the subset of providers that are provided by this module and should be available in other modules which import this module. You can use either the provider itself or just its token (provide value)
More details on modules: https://docs.nestjs.com/modules
