这是Angular 2文档中的一些示例构造函数:
export class AppComponent implements OnInit {
title = 'Tour of heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes() {
this.HeroService.getHeroes().then(heroes => this.heroes = heroes);
}
}
和...
class Car {
constructor(engine, tires, doors){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}
我不明白为什么以及何时创建一个constructor()
angular 2 / typescript(我已经阅读了官方文档,其中他们为Dependency Injection和Services创建了一个构造函数)。
构造函数定义实例化对象时要提供的参数。在TypeScript中,您还可以添加修饰符,例如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
)收集元数据(内的类型或提示@Inject
)以确定要提供给实例化的对象的内容。
请注意,构造函数不是组件生命周期的一部分。稍后可以在此级别上由Angular2设置属性...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句