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

标签 javascript angularjs typescript angular

我是一个刚刚登陆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

只需声明类型为 RouterHeroService 的类的两个私有(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/

相关文章:

javascript - 如何从组件循环向主要父级发出事件 angular 5

php - 通过 location.href 传递 GET

javascript - Google Fusion Tables and Maps - 检测区域中的地址

javascript - 另一个 .js 文件中的异步函数在返回时卡住

angularjs - 如何在具有隔离范围的指令上使用 ng-click?

css - 仅在图像完全下载后显示图像

javascript - “?” 和 javascript 后面的数字是做什么用的?

javascript - AngularJS ng-options 默认选择的选项

node.js - 使用 angular.js 时出现 Injector.modulerr 错误

module - Protractor 和 typescript : Class defined in different file but the same module causes 'declaration exception'