简体   繁体   中英

NestJS: constructor injection with abstract class

I am developing NestJS project with typescript.

I have an abstract class:

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;
  }

}

Then, my concrete class which extends the above abstract class, itself is injected to another caller but that is not a problem so I don't show that here:

@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;
   }
}

When run the code, I get error that the this.config is null in HeavyJobExecutor . Why is that?

Since both abstract class & concrete class need to access that config instance, I prefer to inject it in abstract class' constructor. But how can I access the config in the concrete class?

You can use custom providers

Where you define the provider HeavyJobExecutor

@Module({
  providers: [HeavyJobExecutor],
})
export class SomeExecutorModule {}

replace with

@Module({
  providers: [
    {
      provide: JobExecutor,
      useClass: HeavyJobExecutor,
    },
  ],
})
export class SomeExecutorModule {}

And where you inject this provider, specify the type of the abstract class

constructor(
   private readonly heavyJobExecutor: JobExecutor
) {}

Also you need to add the Injectable decorator to abstract class

@Injectable()
export abstract class JobExecutor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM