NestJS注入的Repository调用方法报错:findByKey未定义
NestJS + Sequelize Repository注入问题:findByKey方法未定义但原型存在
我用NestJS和Sequelize开发API时碰到了一个问题:Service中调用this.repo.findByKey时报错提示该方法未定义,但VSCode调试时明明能看到这个方法存在于原型对象上。
代码复现
service.ts
@Injectable() export class Service { constructor( @Inject('REPOSITORY') private repo: IRepository ) { super(); } async getByCode(code: string) { console.log(this.repo); // 输出:[class Repository extends BaseRepository] console.log(this.repo.findByKey); // 输出:undefined const res = await this.repo.findByKey(code); // 报错:this.repo.findByKey is not a function return res; } }
repository.ts
@Injectable() export class Repository extends BaseRepository implements IRepository { constructor( @Inject('DATABASE_HELPER') databseHelper: DatabaseHelper, private mapper: CountryMapper, ) { super(databseHelper); } async findByKey(code: string): Promise<DTO> { // 代码永远执行不到这里 ... } }
模块配置
@Module({}) export class ExampleModule { static register(typeClass: Type<IService>): DynamicModule { return { imports: [ HelperModule, SequelizeModule.forFeature([Entity]), ], module: ExampleModule, providers: [ ExampleMapper, { provide: 'REPOSITORY', useValue: Repository, }, { provide: 'SERVICE', useClass: typeClass, }, ], controllers: [Controller], }; } }
问题根源
模块配置里的REPOSITORY提供者用了useValue: Repository,这会直接把Repository类本身注入到Service中,而不是类的实例。此时this.repo指向的是构造函数,实例方法findByKey存在于构造函数的原型上,但直接访问构造函数的findByKey属性自然是undefined,必须实例化后才能调用原型方法。
解决方案
把REPOSITORY提供者的useValue改成useClass,让Nest自动负责实例化Repository类并处理其构造函数依赖:
{ provide: 'REPOSITORY', useClass: Repository, }
这样注入的就是Repository的实例,此时访问this.repo.findByKey就能拿到原型上的方法,正常调用不会再报错。
内容的提问来源于stack exchange,提问作者NoneOfYourBusiness
相关产品推荐
相关产品推荐

