Nest can't resolve dependencies of the UserService - javascript

I´m having this error
Nest can't resolve dependencies of the UserService (?, SettingsService). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.
Potential solutions:
- If UserModel is a provider, is it part of the current AuthModule?
- If UserModel is exported from a separate #Module, is that module imported within AuthModule?
#Module({
imports: [ /* the Module containing UserModel */ ]
})
auth.module.ts
#Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: config.auth.secret,
signOptions: {
expiresIn: config.auth.expiresIn,
},
}),
UserModule,
SettingsModule,
],
controllers: [AuthController],
providers: [
AuthService,
JwtStrategy,
LocalStrategy,
UserService,
SettingsService,
Logger,
... other services,
],
exports: [PassportModule, AuthService],
})
export class AuthModule {}
user.module.ts
#Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
SettingsModule,
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
app.module.ts
#Module({
imports: [
AuthModule,
UserModule,
SettingsModule,
MongooseModule.forRoot(config.db.url),
WinstonModule.forRoot({
level: config.logger.debug.level,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
user.service.ts
#Injectable()
export class UserService {
constructor(#InjectModel('User') private readonly userModel: Model<User>,
private readonly settingsService: SettingsService) {}
public async create(user: any): Promise<UserDto> {
...
}
I tried everything and can't find the issue, everything seems correct, i even checked every google page results to try to find it but i'm stuck.
The error tells me that i need to import UserModel into AuthModule, but it's already there, i tried to delete every single user model, or the AuthModule and mix them into everything and it still doesnt work, i know i have to export UserService to AuthModule, but can't find the correct way.

You are providing the UserService in your AuthModule. However, it should only be in your UserModule. In the AuthModule, the UserModel is unknown.

Double-check your module imports:
#Module({
imports: [
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema }
]),
...
],
...
})
export class XModule {}
And look for silly mistakes! because even if you pass schema and schema name instead of each other, there will be no type errors! The general Nest can't resolve dependencies will be all you get for so many mistakes that are probable here...

Related

Use defined value in module provider in other Angular module

I would like use provider value defined in other module. Here is example:
app.module.ts
...
import { ThemeModule } from '../shared/modules/theme/theme.module';
...
#NgModule({
declarations: [
RootComponent,
LoginScreenComponent,
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
BrowserAnimationsModule,
AppRoutingModule,
ConfigModule,
ThemeModule,
....
],
providers: [
...
{ provider: "THEME_NAME", useValue: "VALUE" },
],
bootstrap: [RootComponent]
})
export class MDMToolModule {}
theme.module.ts
import { NgModule } from '#angular/core';
import { ThemeService } from './services/ThemeService';
#NgModule({
imports: [],
declarations: [],
providers: [
{provide: "ThemeService", useFactory: (THEME_NAME) => {
return new ThemeService(THEME_NAME)
}},
],
exports: []
})
export class ThemeModule {}
Is there possibility to pass VALUE defied not in module like above example (THEME NAME)?
if you're providing value in root module then it will be available to all other modules too so you can then simply ask for that value using Inject decorator like this:
#Injectable()
export class ThemeService {
constructor(#Inject("THEME_NAME") theme: string) {}
}
otherwise you can import your MDMToolModule inside ThemeModule though judging by the code you provided I'm assuming this MDMToolModule is your root module,
you can also use Injection Token to avoid using those magic strings like this:
const ThemeName = new InjectionToken("token to inject theme name");
and then use it inside theme.module.ts
#NgModule({
providers: [
{ provide: ThemeName, useValue: "DarkKnight" },
ThemeService
]
})
export class ThemeModule {}
theme.service.ts
#Injectable()
export class ThemeService {
constructor(#Inject(ThemeName) theme: string) {}
}

NestJS - JWTModule context dependency

After run my app i get this...
[Nest] 5608 - 01.01.2021, 18:12:05 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
- If JWT_MODULE_OPTIONS is exported from a separate #Module, is that module imported within JwtModule?
#Module({
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
})
can someone tell me what i have wrong with my code?
#Module({
imports: [TypeOrmModule.forFeature([User]),
JwtModule.register({
secretOrPrivateKey: 'secret12356789'
})
],
providers: [UserService]
})
export class AuthModule { }
#Module({
imports: [
TypeOrmModule.forRoot({
//
}),
AuthModule,
UserModule,
JwtModule
],
controllers: [AppController, UserController, AuthController ],
providers: [AppService, UserService, AuthService ],
})
export class AppModule {}
thanks for any help
///////////////////////////////////////////////////////////////
In your AppModule you have the JwtModule imported but adding no options to it. This is what's causing the issue. As you already have the JwtModule registered in the AuthModule, this probably isn't what you're meaning to do.
You have the UserService registered in at least two places (AuthModule and AppModule), you're probably meaning to add the UserService to the exports of UserModule and then add the UserModule to the imports array of the module where you need the UserService.
TL;DR See, copy/paste examples.
Recently had the same issue.
As Nest.JS recommends the JwtModule could be declared in an authorization module: https://docs.nestjs.com/security/authentication. And, yes, it should be declared once with all its settings. The topic message could come from a multiple declaration (some of them has no JWT_MODULE_OPTIONS). Can wrap Jay's response with a prepared working example.
So the auth module should look like:
//./authorization/authorization.module.ts
import { Module } from '#nestjs/common';
import { JwtModule } from '#nestjs/jwt';
import { AuthorizationController } from './authorization.controller';
import { AuthorizationService } from './authorization.service';
#Module({
imports: [
...
JwtModule.register({
secret: process.env.ACCESS_TOKEN_SECRET || 'SOME_SECURE_SECRET_jU^7',
signOptions: {
expiresIn: process.env.TOKEN_EXPIRATION_TIME || '24h',
}
}),
....
],
controllers: [AuthorizationController],
providers: [AuthorizationService],
exports: [AuthorizationService, JwtModule]//<--here exports JwtModule
//as a part of AuthorizationModule
})
export class AuthorizationModule {};
Then your AppModule will inject the exported JwtModule from AuthorizationModule in this way.
//./app.module.js
import { Module } from '#nestjs/common';
import { AuthorizationModule } from './authorization/authorization.module';
#Module({
imports: [
...
AuthorizationModule, //<-- here injects the set up JwtModule
//NB! No additional injections required!
...
],
...
})
export class AppModule {};
Hope, this will help. ;)

Modules in NestJS

Can someone tell me why i have this error:
[Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
- If JWT_MODULE_OPTIONS is exported from a separate #Module, is that module imported within JwtModule?
#Module({
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
})
my modules:
#Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt'}),
JwtModule.register({
secret: 'topSecret51',
signOptions: {
expiresIn: 3600
},
}),
TypeOrmModule.forFeature([User])
],
controllers: [AuthController],
providers: [AuthService, UserService]
})
export class AuthModule {}
#Module({
controllers: [UserController],
providers: [UserService, AuthService],
imports: [AuthModule]
})
export class UserModule {}
#Module({
imports: [
TypeOrmModule.forRoot(typeOrmConfig),
UserModule,
AuthModule
],
})
export class AppModule {}
i try to change in all of them but in all of them my app does not work
thanks for any help
////////////////////////////////////////////////////
If you are using some dependencies of the controller in JwtService, you need to add JWT_MODULE_OPTIONS as provider inside the current AuthModule. Have a look at the nestjs documentation. They have explained on how to register custom providers.
I received this error when I did not correctly import / initialize the JwtModule. The JwtModule should handle the JwtService initialization which this error comes from. I would start there. If you're using the AuthModule in your test environment which by extension needs the JwtModule then you'll need to manually define your JwtModule with something similar:
beforeAll(async () => {
const testingModule: TestingModule = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
MongooseModule.forFeature([{ name: 'User', schema: userSchema }]),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: { expiresIn: '1d' }
})
}),
],

NestJS can't resolve dependencies of the AuthServices

After first problem with JWT_MODULE_OPTION, back to old problem who I thought I was fixed. It turned out that when I "fix" old problem create the new with JWT.
So again can't compile:
Nest can't resolve dependencies of the AuthService (?, RoleRepository, JwtService). Please make sure that the argument at index [0] is available in the AppModule context. +25ms
It's really strange, because this way work on another my project and can't understand where I'm wrong. Here is the auth.service.ts:
#Injectable()
export class AuthService {
constructor(
#InjectRepository(User) private readonly userRepo: Repository<User>,
#InjectRepository(Role) private readonly rolesRepo: Repository<Role>,
private readonly jwtService: JwtService,
) { }
It get role and jwtService but the problem is with User, the path is correct. Here is app.module.ts:
#Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule, AuthModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
type: configService.dbType as any,
host: configService.dbHost,
port: configService.dbPort,
username: configService.dbUsername,
password: configService.dbPassword,
database: configService.dbName,
entities: ['./src/data/entities/*.ts'],
}),
}),
],
controllers: [AppController, AuthController],
providers: [AuthService],
})
export class AppModule { }
Have the same compile error for controllers & providers & can't understand what is wrong...
You might be missing the TypeOrmModule.forFeature([User]) import. Typically, all entities are imported in dedicated feature modules. If you only have one module (i.e. AppModule) you need to put the forFeature import there in addition to the forRoot import.
#Module({
imports: [
TypeOrmModule.forRootAsync({...}),
TypeOrmModule.forFeature([User, Role]),
],
The global problem was that I try to add AuthService & AuthController twice. So I remove them from app.module.ts and just export AuthService from auth.module.ts:

Invalid provider error when injecting service into service in Angular 2

I currently have a module setup like below (exerpt);
AppModule
RoutingModule
AuthRouteGuard
AuthModule
LoginFormComponent
AuthService
I have defined my AuthService (responsible for handling user authentication and provides a method for determining whether the current user is authenticated) as a provider in my AuthModule;
// auth.module.ts - uses https://github.com/auth0/angular2-jwt
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: jwtLocalStorageKey
}), http, options);
}
export let authHttpServiceProvider = {
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
};
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService,
authHttpServiceProvider
]
})
export class AuthModule { }
I can use this service with no problem within its sibling LoginFormComponent. When I attempt to use the AuthService within the AuthRouteGuard class in the RoutingModule however I get the following error;
Error: Invalid provider for the NgModule 'AuthModule' - only instances of Provider and Type are allowed, got: [?undefined?, ...]
I have the AuthModule imported within the RoutingModule. The error above occurs as soon as the AuthService is defined as a dependency for the AuthRouteGuard;
export class AuthRouteGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService // Removing this injection removes the error
) {}
canActivate() {
// #todo: if not authenticated
this.router.navigate(['/login']);
return true;
}
}
What am I missing here, and why would injecting the service in the constructor cause an invalid provider error that does not occur when that injection is removed?
Edit - Same error occurs if the authHttpServiceProvider provider is removed altogether, so the AuthModule module looks like;
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule { }
Add authHttpServiceProvider to imports of the module. It's exported to global and not available to module. So you can't provide the service because you have unknown provider to the module.
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule {
The actual problem was within the AuthService itself.
AuthModule defined a constant;
export const jwtKey = 'jwt';
Which was being imported into the AuthService and used;
import { jwtKey } from '../auth.module';
For some reason if I remove this import everything works fine.

Categories