2017-08-07 106 views
1

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

我怎么称呼它:

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这两种方法没有区别。

有人可以解释我是什么原因?

谢谢。

+0

你为什么不在这里使用'new'关键词this.accidentMap = AccidentMapContent(...'? –

+0

我编辑了我的信息,其实这是我的复制/粘贴错误,谢谢 – Booleon

+0

这两个是等效的,所以我的猜测是其他事情是错误的。发布一个完整的,最小化的例子来重现问题。 –

回答

0

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

当我宣布在构造函数参数的服务,这些服务将可用于变量要不然的话初始化,当我宣布在构造函数中的服务,该变量初始化会前服务初始化leadind occure到崩溃:

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) { } 

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

相关问题