【问题标题】:Nestjs Subscriber +TypeOrm Injection through yml filesNestjs订阅者+TypeOrm通过yml文件注入
【发布时间】:2021-11-25 20:46:25
【问题描述】:

我们如何将订阅者的连接依赖注入到 yml 文件中。

我的文件是: ormconfig.yml

default:
    type: 'postgres'
    host: 'localhost'
    port: 5432
    username: 'postgres'
    password: 'root'
    database: 'hiring_db'
    entities: ["dist/**/*.entity{.ts,.js}"]
    synchronize: true
    logging: ["query","error"]
    logger: "file"
    extra: { timezone: "+5:30" }
    migrations: ["src/migrations/*.ts"]
    cli:   {
        migrationDir: 'src/migrations'
    }
    subscribers: ["src/**/*.subscriber{.ts,.js}"]

JobPostingModule.ts

import { Module } from '@nestjs/common';
import { JobPostingController } from './job-posting.controller';
import { JobPostingService } from './job-posting.service';
import { AuthModule } from '../auth/auth.module';
import { RecruitmentService } from '../recruitment/recruitment.service';

@Module({
  imports: [
    AuthModule
  ],
  controllers: [JobPostingController],
  providers: [JobPostingService, RecruitmentService]
})
export class JobPostingModule {}

JobSubscriber.ts

import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { Jobs } from 'src/entities/job-posting.entity';
import { Connection, EntitySubscriberInterface, getConnection, InsertEvent, UpdateEvent } from 'typeorm';
import { JobPostingService } from './job-posting.service';


@Injectable()
export class JobSubscriber implements EntitySubscriberInterface {
  
  constructor(private readonly connection: Connection) {
    connection.subscribers.push(this); // <---- THIS 
   
}

  listenTo() {
    return Jobs;
  }

  afterInsert(event: InsertEvent<Jobs>) {
    console.log('Hi guys!');
  };

  afterUpdate(event: UpdateEvent<any>) {
    console.log('Hi guys!');
  }

}

我收到此错误 Nest 无法解析 JobSubscriber (?) 的依赖关系。请确保索引 [0] 处的参数 Connection 在 AppModule 上下文中可用。

Potential solutions:
- If Connection is a provider, is it part of the current AppModule?
- If Connection is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing Connection */ ]
  })

【问题讨论】:

    标签: node.js nestjs typeorm


    【解决方案1】:

    You can refer to the official NestJS documentation for this problem.

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    
    @Module({
      imports: [
        TypeOrmModule.forRoot(),
      ],
    })
    export class AppModule {}
    

    导入TypeOrmModule 后,您可以在任何地方使用Connection 作为提供程序。

    【讨论】:

    • 在你的解决方案之后我得到这个 TypeError: Cannot read property 'push' of undefined
    • 抱歉,编辑了我的答案以更好地解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2020-03-29
    • 2019-07-05
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多