我尝试使用 registerAsync 导入模块并使用模块中的提供程序配置它,但它会抛出错误,无法找到该提供程序。我缺少什么?
我的代码:
import { CacheModule, Module } from '@nestjs/common';
@Module({
imports: [
CacheModule.registerAsync({
useFactory: async (options) => ({
ttl: options.ttl,
}),
inject: ['MY_OPTIONS'],
}),
],
providers: [
{
provide: 'MY_OPTIONS',
useValue: {
ttl: 60,
},
},
],
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
错误:
错误:Nest 无法解析 CACHE_MODULE_OPTIONS 的依赖关系(?)。请确保索引 [0] 处的参数 MY_OPTIONS 在 CacheModule 上下文中可用。
上面的例子是我的代码的简化。但主要问题保持不变:我在 AppModule 中有一个提供程序,并且我在 CacheModule.registerAsync() 函数中需要它。
如果有人想尝试解决这个问题,我做了一个非常简单的存储库:https ://github.com/MickL/nestjs-inject-existing-provider
假设我的模块定义如下:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
// Use ConfigService here
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
PrismaModule,
],
providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)
现在我怎样才能secretKey从ConfigService这里得到?
在我的主模块 (A) 中,我导入外部模块 (B) 及其配置:
imports: [
NestAuthModule.registerAsync({
inject: [authConfig.KEY],
useFactory: async (config: ConfigType<typeof authConfig>) => ({
google: config.google,
jwt: config.jwt,
}),
})
]
Run Code Online (Sandbox Code Playgroud)
export class NestAuthModule {
static registerAsync(options: AuthModuleAsyncOptions): DynamicModule {
return this.createModule(
this.createAsyncProviders(options),
options.imports || []
);
}
private static createModule(
providers: Provider[],
imports: Array<
Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference
>
) {
return {
module: NestAuthModule,
controllers: [AuthController],
providers: [
...providers
],
imports: [
...imports,
JwtModule.registerAsync({
inject: [AuthModuleOptions],
useFactory: async (options: AuthModuleOptions) => { …Run Code Online (Sandbox Code Playgroud)