在构造函数angular 2中声明属性

Rob*_*iaz 4 javascript angularjs typescript angular

我是一个刚刚登陆角度2的java程序员.在做官方教程时,我很惊讶地看到他们在构造函数中声明了这个属性而不是类的顶层.

我知道Java和JS是非常不同的,但在这样做之间有任何技术原因

  constructor(private router: Router ,private heroService: HeroService) {}
Run Code Online (Sandbox Code Playgroud)

或者像这样

private router: Router
private heroService: HeroService

constructor( ) {}
Run Code Online (Sandbox Code Playgroud)

lex*_*ith 9

这个:

private router: Router
private heroService: HeroService
Run Code Online (Sandbox Code Playgroud)

只是声明类类型的两个私人性质RouterHeroService,

这个:

constructor(private router: Router, private heroService: HeroService) {}
Run Code Online (Sandbox Code Playgroud)

注入Router(和HeroService)的实例,另外创建两个私有属性,并在一个语句中将注入的服务实例分配给这些属性.

为了更好地理解,这也是一样的:

private _router: Router;
private _heroService: HeroService;

constructor(router: Router, heroService: HeroService) {
    this._router = router;
    this._heroService = heroService;
}
Run Code Online (Sandbox Code Playgroud)

使用"第一种方法",您没有这些服务的实例.

旁注:providers: [Router, HeroService]你可能在某个地方的某处Component Anntations只是给你的组件注入它们的可能性,但实际上并没有这样做,这就是为什么你可能最终总是通过你的constructor方法注入它们.