gpt4 book ai didi

typescript - 使用 registerAsync 导入模块时,Nest 无法解析依赖项

转载 作者:行者123 更新时间:2023-12-04 12:56:40 28 4
gpt4 key购买 nike

我尝试使用 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 {
}
错误:

Error: Nest can't resolve dependencies of the CACHE_MODULE_OPTIONS (?). Please make sure that the argument MY_OPTIONS at index [0] is available in the CacheModule context.


上面的例子是我的代码的简化。但主要问题保持不变:我在 AppModule 中有一个提供程序,我在 CacheModule.registerAsync() 函数中需要它。
如果有人想尝试解决这个问题,我创建了一个非常简单的存储库: https://github.com/MickL/nestjs-inject-existing-provider

最佳答案

我会说问题是“CacheModule.registerAsync”和“AppModule”在不同级别工作,因此在“AppModule”上定义提供程序并不能使其可用于“CacheModule.registerAsync”。
假设我们将“MY_OPTIONS”移动到另一个模块:“CacheConfigModule”,它可能看起来像:
CacheConfigModule.ts

import { Module } from '@nestjs/common';

@Module({
providers: [
{
provide: 'MY_OPTIONS',
useValue: {
ttl: 60
}
}
],
exports: ['MY_OPTIONS']
})
export class CacheConfigModule {}
AppModule.ts
import { CacheModule, Module } from '@nestjs/common';
import { CacheConfigModule } from './CacheConfigModule';

@Module({
imports: [
CacheConfigModule,
CacheModule.registerAsync({
imports: [CacheConfigModule],
useFactory: async (options) => ({
ttl: options.ttl
}),
inject: ['MY_OPTIONS']
})
]
})
export class AppModule {}

关于typescript - 使用 registerAsync 导入模块时,Nest 无法解析依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65968652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com