【发布时间】: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