You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular独立模式下index.ts导出指令出现初始化前访问错误

Angular独立模式下index.ts导出指令触发「Cannot access 'SomeDirective' before initialization」问题解决

问题描述

在Angular独立模式(所有组件、指令均设置standalone: true)下,通过index.ts批量导出指令时,出现「Cannot access 'SomeDirective' before initialization」错误,但直接从指令文件导入则可正常运行。

相关代码

BaseDirective基类

export class BaseDirective implements OnInit {

  protected baseModel: BaseModel = 
  { id: '', type: Type.Undefined };

  ngOnInit(): void {
    // do base stuff
  }

  protected baseFunction() {
    console.log('gets overwritten');
  }

}

SomeDirective子类

export class SomeDirective extends BaseDirective {

  protected customerDetailsService = inject(CustomerDetailsService);

  constructor() {
    super();
  }

  protected override baseFunction(): void {
    // do something
  }

}

index.ts导出文件

export * from './base/base.directive';
export * from './some/some.directive';
export * from './base/base.model';

问题原因

核心问题在于export *的模块合并机制与Angular独立组件/指令的初始化顺序冲突:

  1. 当通过index.ts导入时,TypeScript会将所有export *的内容合并到一个模块中,若导出顺序不合理,会导致子类(SomeDirective)在父类(BaseDirective)或父类依赖的模型(BaseModel)完成初始化前被引用。
  2. SomeDirective中直接在类属性上使用inject(),该调用会在构造函数执行前触发,进一步加剧了初始化顺序的矛盾——父类构造函数执行时,子类的依赖注入逻辑可能还未完成。

解决方案

1. 调整index.ts的导出顺序

确保父类依赖的模型、父类、子类按顺序导出,保证初始化依赖链的完整性:

// 先导出父类依赖的模型
export * from './base/base.model';
// 再导出父类指令
export * from './base/base.directive';
// 最后导出子类指令
export * from './some/some.directive';

2. 改用显式导出替代export *

显式指定导出项,让TypeScript更清晰地解析依赖关系,避免隐式的模块合并问题:

export { BaseModel } from './base/base.model';
export { BaseDirective } from './base/base.directive';
export { SomeDirective } from './some/some.directive';

3. 调整inject()的调用时机

将inject()移到构造函数中,确保在父类构造函数执行完成后再进行依赖注入:

export class SomeDirective extends BaseDirective {

  protected customerDetailsService: CustomerDetailsService;

  constructor() {
    super();
    this.customerDetailsService = inject(CustomerDetailsService);
  }

  protected override baseFunction(): void {
    // do something
  }

}

内容的提问来源于stack exchange,提问作者Basti-V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:00:46