【问题标题】:Lazy loading with DI into base class使用 DI 延迟加载到基类中
【发布时间】:2016-05-06 01:54:27
【问题描述】:

情况:

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

问题:

服务是Base 中的undefined。除非我 console.log(_service) 先于基类。我怀疑与通过 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) 出现错误:

异常:Main 实例化期间出错!

原始异常:TypeError:无法读取未定义的属性“doSomething”

但是,如果我尝试追踪为什么 _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
    }
}

【问题讨论】:

    标签: typescript angular angular2-services


    【解决方案1】:

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

    interface IService{
       doSomething();
    }
    

    现在修改基类如下。

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

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

    【讨论】:

    • 我应该包含服务类 - 它是静态的,这就是问题所在。看我的回答。感谢您的帮助。
    【解决方案2】:

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

    这就是console.log“修复”它的原因——它在console.log() 语句中被实例化,然后及时存在以供实际使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      相关资源
      最近更新 更多