我正在用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;
}
}
然后,我的具体类扩展了上面的抽象类,它本身被注入到另一个调用者中,但这不是问题,所以我在这里没有显示:
@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;
}
}
当运行代码时,我得到this.config
在HeavyJobExecutor
中为空的错误。为什么呢?
因为抽象类&具体类需要访问config
实例,我更喜欢在抽象类的构造函数中注入它。但是我如何在具体类中访问config
呢?
您可以使用自定义提供程序
定义提供程序的地方HeavyJobExecutor
@Module({
providers: [HeavyJobExecutor],
})
export class SomeExecutorModule {}
替换为
@Module({
providers: [
{
provide: JobExecutor,
useClass: HeavyJobExecutor,
},
],
})
export class SomeExecutorModule {}
在注入此提供程序的地方,指定抽象类的类型
constructor(
private readonly heavyJobExecutor: JobExecutor
) {}
还需要将Injectable
装饰器添加到抽象类
@Injectable()
export abstract class JobExecutor