【问题标题】:Why can't I declare DI outside of construtor Angular2?为什么我不能在构造函数 Angular2 之外声明 DI?
【发布时间】:2017-08-07 08:11:39
【问题描述】:

我有一个由服务实例化的类(但不是服务本身),并且需要多个服务才能工作。 如果我在构造函数之外声明我需要的每个服务,我会收到一条错误消息,告诉我我的服务未定义。

我怎么称呼它:

export class MapContentService {
  public accidentMap: AccidentMapContent;
  ...    
  constructor(private httpRequestService: HttpRequestService, private translate: TranslateService, private conf: ConfigurationService) { }
  ...
  public getMapContent(): Promise<MapContentInterface> {
    ...        
    this.accidentMap = new AccidentMapContent(this.httpRequestService, this.translate, this.conf);
  }

它是如何不起作用的:

export class AccidentMapContent implements MapContentInterface {
  ...
  private conf: ConfigurationService;
  private translate: TranslateService;
  private httpRequestService: HttpRequestService;
  ...
  constructor( httpRequestService: HttpRequestService, translate: TranslateService, conf: ConfigurationService) { 
    this.conf = conf;
    this.translate = translate;
    this.httpRequestService = httpRequestService;
  }

它是如何工作的:

export class AccidentMapContent implements MapContentInterface {
  ...    
  constructor(private httpRequestService: HttpRequestService, private translate: TranslateService, private conf: ConfigurationService) { }

如果我们遵循构造函数逻辑,两者都应该正常工作。我不明白为什么它已被覆盖。见这篇帖子:declare properties in constructor angular 2这两种方法没有区别。

谁能解释一下这是什么原因?

谢谢。

【问题讨论】:

  • 你为什么不在这里使用new关键字this.accidentMap = AccidentMapContent(...
  • 我编辑了我的消息。实际上是我的复制/粘贴错误。谢谢。
  • 两者是等价的,所以我的猜测是还有其他问题。发布一个完整的、最小的示例来重现该问题。

标签: angular typescript dependency-injection constructor


【解决方案1】:

我终于找到了发生的事情。 感谢@JB Nizet 的评论,我做了进一步的调查。其中一个变量是使用其中一项服务启动的。

当我在构造函数参数中声明服务时,服务将可用于初始化变量,否则,当我在构造函数中声明服务时,变量初始化将在服务初始化之前发生,导致崩溃:

export class AccidentMapContent implements MapContentInterface {
  ...
  // The faulty line : 
  private icon: MapPointIcon = new MapPointIcon(this.conf.mapConf.ICON_SIZE, this.conf.mapConf.ICON_OFFSET, this.conf.mapConf.ICON_URL);
  ...    
  constructor(private httpRequestService: HttpRequestService, private translate: TranslateService, private conf: ConfigurationService) { }

解决方案:我将变量初始化也移到构造函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多