我正在使用Nest 7.1.5和ioredis 4.17.3。我正在尝试创建一个 RedisService 并在之后注入它。 这是我到目前为止所拥有的:
redis.providers.ts
import { Provider } from '@nestjs/common';
import Redis from 'ioredis';
import { REDIS_CLIENT } from './redis.constants';
export type RedisClient = Redis.Redis;
export const redisProviders: Provider[] = [
{
useFactory: (): RedisClient => {
return new Redis({
host: 'localhost',
port: 6379,
});
},
provide: REDIS_CLIENT,
}
]
redis.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { REDIS_CLIENT } from './redis.constants';
import { RedisClient } from './redis.providers';
@Injectable()
export class RedisService {
public constructor(
@Inject(REDIS_CLIENT)
private readonly redisClient: RedisClient,
) { }
}
redis.module.ts
import { Module } from '@nestjs/common';
import { redisProviders } from './redis.providers';
import { RedisService } from './redis.service';
@Module({
providers: [...redisProviders, RedisService],
exports: [...redisProviders, RedisService],
})
export class RedisModule { }
当我尝试注入此服务时,出现此错误:
[12:25:57 PM] Found 0 errors. Watching for file changes.
/path/redis-setup/dist/shared/redis/redis.service.js:28
__metadata("design:paramtypes", [typeof (_a = typeof redis_providers_1.RedisClient !== "undefined" && redis_providers_1.RedisClient) === "function" ? _a : Object])
^
ReferenceError: redis_providers_1 is not defined
at /path/redis-setup/dist/shared/redis/redis.service.js:28:62
at Object.<anonymous> (/path/redis-setup/dist/shared/redis/redis.service.js:31:3)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Module.require (internal/modules/cjs/loader.js:723:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/path/redis-setup/dist/app.service.js:14:25)
at Module._compile (internal/modules/cjs/loader.js:816:30)
我在这里错过了什么?任何帮助或想法不胜感激。谢谢。
您需要安装类型
npm install @types/ioredis --save-dev
然后在代码中,您必须从 RedisClient 更改为简单的 Redis。在最新版本中,没有RedisClient作为类型。
import Redis from 'ioredis';
.....
export type RedisClient = Redis.Redis;
尝试在tsconfig.json中添加"esModuleInterop": true