NestJS:带有抽象类的构造函数注入

use*_*225 5 abstract-class node.js typescript nestjs

我正在使用 typescript 开发 NestJS 项目。

我有一个抽象类:

export abstract class JobExecutor {

  private readonly name: string;

  constructor(
    // I injected the JobConfig instance in constructor
    protected readonly config: JobConfig,
  ) {
    this.name = this.getName();
  }
  
  abstract getName(): string;

  // non-abstract method also needs to access `config`
  doJob = async ()=> {
    const configMetaData = this.config.metadata;
  }

}
Run Code Online (Sandbox Code Playgroud)

然后,我的具体类扩展了上述抽象类,它本身被注入到另一个调用者,但这不是问题,所以我不在这里显示:

@Injectable()
export class HeavyJobExecutor extends JobExecutor {
   //implement the abstract method
   getName(): string {
       // it accesses the injected `config` from the abstract class,
       // BUT at runtime, this.config is null, why?
       return this.config.heavyjob.name;
   }
}
Run Code Online (Sandbox Code Playgroud)

运行代码时,我收到错误,this.config其中 为 null HeavyJobExecutor。这是为什么?

由于抽象类和具体类都需要访问该config实例,因此我更喜欢将其注入抽象类的构造函数中。但是我如何访问config具体类中的?

Bek*_*azy 8

您可以使用自定义提供程序

您定义提供者的位置HeavyJobExecutor

@Module({
  providers: [HeavyJobExecutor],
})
export class SomeExecutorModule {}
Run Code Online (Sandbox Code Playgroud)

用。。。来代替

@Module({
  providers: [
    {
      provide: JobExecutor,
      useClass: HeavyJobExecutor,
    },
  ],
})
export class SomeExecutorModule {}
Run Code Online (Sandbox Code Playgroud)

在注入此提供程序的位置,指定抽象类的类型

constructor(
   private readonly heavyJobExecutor: JobExecutor
) {}
Run Code Online (Sandbox Code Playgroud)

您还需要将Injectable装饰器添加到抽象类中

@Injectable()
export abstract class JobExecutor
Run Code Online (Sandbox Code Playgroud)