何时在Angular2 typescript中创建构造函数?
以下是来自的一些示例构造函数: 而且何时在Angular2 typescript中创建构造函数?,typescript,angular,Typescript,Angular,以下是来自的一些示例构造函数: 而且 class Car { constructor(engine, tires, doors){ this.engine = engine; this.tires = tires; this.doors = doors; } } 我不明白为什么以及何时在angular 2/typescript中创建构造函数()(我已经阅读了官方文档,其中他们为依赖项注入和服务创建了一个构造函数)。控制器构造函数主
class Car {
constructor(engine, tires, doors){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}
我不明白为什么以及何时在angular 2/typescript中创建
构造函数()
(我已经阅读了官方文档,其中他们为依赖项注入和服务创建了一个构造函数)。控制器构造函数主要用于依赖项注入/服务,如您所述,而且(在我的应用程序中)用于基于服务本身初始化复杂的默认值。由于构造函数在控制器模板初始化之前运行,因此不会准确呈现任何变量,因此需要使用ngOnInit
和其他类似方法。这些“引导”方法应用于执行正常的“构造”任务,以便模板/视图可以访问数据
关于服务构造函数,我的一些人通常使用构造函数,并根据现有用户数据初始化服务的各个部分,因为它们的行为更像标准类
这些答案将有所帮助:
private
或public
,以便在同一时间定义类属性,并使用提供的属性设置其值
例如:
class Car {
constructor(private engine:string, private tires:string, private doors:number){
}
}
类似于:
class Car {
constructor(engine:string, tires:string, doors:number){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}
在Angular2中,构造函数用于依赖项注入。关联的装饰器(@Component
或Injectable
)收集元数据(在@injection
中的类型或提示),以确定向要实例化的对象提供什么
请注意,构造函数不是组件生命周期的一部分。属性稍后可由Angular2在此级别设置…+1。我很难知道构造函数中应该包含什么(除了“尽可能少”)和不应该包含什么。我想这是一个更广泛的编程概念,但我的阅读并没有产生任何特别清晰的内容,用一种简单的方式描述构造函数及其用途。嗨,Sarvesh,如果您将代码作为文本插入,对其他人可能会更好。@J.Chomel我认为现在更好:)我编辑了这篇文章,以使其更清晰,并使用代码而不是图像作为示例。有关您可以使用的示例,请参见打字脚本操场上的。
class Car {
constructor(engine:string, tires:string, doors:number){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}