我是一个刚刚登陆angular 2的java程序员,在做官方教程的时候,看到他们在构造函数中声明这个属性,而不是类的顶部,我很惊讶。
我知道 Java 和 JS 有很大的不同,但是这样做之间有什么技术上的原因吗
constructor(private router: Router ,private heroService: HeroService) {}
或者像这样
private router: Router
private heroService: HeroService
constructor( ) {}
最佳答案
同时:
private router: Router
private heroService: HeroService
只需声明类型为 Router
和 HeroService
的类的两个私有(private)属性,
这个:
constructor(private router: Router, private heroService: HeroService) {}
注入(inject) Router
(和 HeroService
)实例,另外创建两个私有(private)属性,并在一条语句中将注入(inject)的服务实例分配给它们。
为了更好地理解,这也是一样的:
private _router: Router;
private _heroService: HeroService;
constructor(router: Router, heroService: HeroService) {
this._router = router;
this._heroService = heroService;
}
使用“第一种方法”,您没有这些服务的实例。
旁注:providers: [Router, HeroService]
你可能在你的 Component Anntations
中的某个地方只是给你的组件注入(inject)它们的可能性,但不是实际上并没有这样做,这就是为什么您最终可能总是通过 constructor
方法注入(inject)它们。
关于javascript - 在构造函数angular 2中声明属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211775/