NestJS Nest can';t解析用户服务的依赖关系
我正在尝试创建我的自定义NestJS Nest can';t解析用户服务的依赖关系,nestjs,Nestjs,我正在尝试创建我的自定义JwtModule。我制作了JwtModule动态模块,以便使用dotenv提供私钥 jwt.module.ts: 从'@nestjs/common'导入{DynamicModule,Module}; 从“./jwt.constants”导入{CONFIG_OPTIONS}; 从“/jwt.interfaces”导入{JwtModuleOptions}; 从“/jwt.service”导入{JwtService}; @模块({}) 导出类JWT模块{ 静态forRoot(
JwtModule
。我制作了JwtModule
动态模块,以便使用dotenv
提供私钥
jwt.module.ts:
从'@nestjs/common'导入{DynamicModule,Module};
从“./jwt.constants”导入{CONFIG_OPTIONS};
从“/jwt.interfaces”导入{JwtModuleOptions};
从“/jwt.service”导入{JwtService};
@模块({})
导出类JWT模块{
静态forRoot(选项:JwtModuleOptions):动态模块{
返回{
模块:JWT模块,
供应商:[
{
提供:配置_选项,
useValue:选项,
},
JwtService,
],
导出:[JwtService],
};
}
}
jwt.service.ts:
从'@nestjs/common'导入{Inject,Injectable};
从“./jwt.constants”导入{CONFIG_OPTIONS};
从“/jwt.interfaces”导入{JwtModuleOptions};
@可注射()
导出类JWTS服务{
建造师(
@注入(配置选项)私有只读选项:JwtModuleOptions,
) {}
//我会在这里做点什么
}
users.module.ts:
从'@nestjs/common'导入{Module};
从'@nestjs/typeorm'导入{TypeOrmModule};
从'src/jwt/jwt.module'导入{JwtModule};
从“./entities/User.entity”导入{User};
从“./users.resolver”导入{UsersResolver};
从“/users.service”导入{UsersService};
@模块({
导入:[TypeOrmModule.forFeature([User]),JwtModule],
提供者:[UsersResolver,UsersService],
})
导出类UsersModule{}
users.service.ts:
从'@nestjs/common'导入{Injectable};
从'@nestjs/typeorm'导入{InjectRepository};
从'src/common/common.constants'导入{InternalServerErrorOutput};
从'src/jwt/jwt.service'导入{JwtService};
从“typeorm”导入{Repository};
进口{
CreateAccountInput,
CreateAccountOutput,
}来自“./dtos/create account.dto”;
从“./entities/User.entity”导入{User};
@可注射()
导出类用户服务{
建造师(
@注入存储库(用户)
私有只读用户存储库:存储库,
专用只读jwtService:jwtService,
) {}
//我会在这里做点什么
}
我将JwtModule导入到app.module.ts
中,如下所示:
JwtModule.forRoot({privateKey:process.env.JWT_PRIVATE_KEY})
但是,当我尝试运行此应用程序时,控制台会打印一个错误:
Nest can't resolve dependencies of the UsersService (UserRepository, ?).
Please make sure that the argument JwtService at index [1] is available in the UsersModule context.
Potential solutions:
- If JwtService is a provider, is it part of the current UsersModule?
- If JwtService is exported from a separate @Module, is that module imported within UsersModule?
@Module({
imports: [ /* the Module containing JwtService */ ]
})
由于我导出了
JwtService
并将JwtModule
导入到UsersModule
中,因此错误提示没有帮助。使用@Global
到JwtModule
是一个简单的解决方案,但由于我不会在其他地方使用JwtModule,因此我想知道不使其全球化的方法。任何帮助都将不胜感激。谢谢大家! 动态模块就是这样,动态的。当它们即将被使用时,需要调用它们的配置/注册方法。您在AppModule
中注册了JwtModule
,但没有在UserModule
中注册,因此UserModule
不会看到导出了JwtService
的返回模块,它会看到没有提供程序和导出的模块。有两种方法可以解决这个问题
UserModule
中注册JwtModule
,如果不打算重复使用,这可能不是一个坏主意
JwtModule.forRoot()
并导出JwtModule
,然后在需要JwtModule
的地方导入包装器模块,并每次都返回配置的模块
JwtMoule.externallyConfigured(0)
的操作,并获得在AppModule
中进行的配置。又一次,杀伤力过大,但很酷