在构造函数angular 2中声明属性 [英] declare properties in constructor angular 2

查看:83
本文介绍了在构造函数angular 2中声明属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a java programer that just has landed in angular 2. When doing the official tutorial, I was surprised to see that they declare this properties in the constructor instead of the top of the class.

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

I know that Java and JS are very different but is there any technical reason between doing like this

  constructor(private router: Router ,private heroService: HeroService) {}

或者像这样

private router: Router
private heroService: HeroService

constructor( ) {}


推荐答案

虽然这样:

private router: Router
private heroService: HeroService

只声明类型的两个私有属性路由器 HeroService

just declares two private properties of your class of type Router and HeroService,

这个:

constructor(private router: Router, private heroService: HeroService) {}

注入路由器(以及 HeroService ),另外创建两个私有属性,并在一个语句中将注入的服务实例分配给这些属性。

injects an instance of Router (and HeroService), additionally creates two private properties and assigns the injected instances of your services to these in one statement.

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

For a better understanding, this does the same:

private _router: Router;
private _heroService: HeroService;

constructor(router: Router, heroService: HeroService) {
    this._router = router;
    this._heroService = heroService;
}

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

With the "first approach" you don't have an instance of these services.

旁注:提供商:[路由器,HeroService] 你可能在某个 Component Anntations 只是给你的组件注入它们的可能性,但实际上并没有这样做,这就是为什么你可能最终总是通过你的构造函数注入它们方法。

Sidenote: providers: [Router, HeroService] which you might have somewhere in one of your Component Anntations just give your components the possibility to inject them, but doesn't actually do it, that's why you probably end up injecting them always via your constructor method.

这篇关于在构造函数angular 2中声明属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆