使用 DI 延迟加载到基础 class

Lazy loading with DI into base class

情况:

我有一个基地 class BaseMain 扩展 BaseMain 通过 super() 将服务传递给 BaseBase 然后调用该服务的方法。

问题:

服务是 Base 中的 undefined。除非我console.log(_service)之前在基地class。我怀疑与通过 AsyncRoute 延迟加载有关的竞争条件,或者它可能是一个实例化问题......无论哪种方式,我都不确定如何开始纠正它。

Main.ts:

export class Main extends Base {
    constructor(private _service:SomeService) {
        super(this._service);
    }
}

Base.ts:

@Injectable()
export class Base {
    constructor(_service) {
        _service.doSomething(true);
    }
}

代码在 _service.doSomething(true) 处爆炸并出现错误:

EXCEPTION: Error during instantiation of Main!

ORIGINAL EXCEPTION: TypeError: Cannot read property 'doSomething' of undefined

但是,如果我尝试通过以下操作来追踪 _service 未定义的原因 - 它神奇地起作用了???

Base.ts:

@Injectable()
export class Base {
    constructor(_service) {
        console.log("_service?", _service); // if this is here...
        _service.doSomething(true);  // ...then the error no longer occurs here
    }
}

您可以使用服务接口来解决此问题,如下所示。

interface IService{
   doSomething();
}

现在修改基数class如下。

export class Base {
constructor(_service: IService) {
    _service.doSomething(true); 
  }
}

注意:SomeService 应该实现 IService 希望这能解决您的问题。

问题是我使用的是静态服务,所以我应该一直在做 SomeService.doSomething() 而不是像 _service:SomeService 那样尝试实例化它。

这就是 console.log "fixed" 它的原因 - 它在 console.log() 语句中被实例化,然后在实际使用时及时存在。