【发布时间】:2017-06-02 14:04:40
【问题描述】:
我是 Angular 2 和 Typescript 的新手,并试图理解 DI。在我看到的所有代码中,我看到引用服务的变量被输入到构造函数中。这是为什么?为什么我们不能在构造函数之外而是在类中声明它?
考虑以下来自《英雄之旅》的代码,例如在 Angular 网站上:
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: `dashboard.component.html`,
styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
如果我像下面这样在构造函数之外声明 heroService,应用程序会抛出很多错误。
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor() { }
private heroService: HeroService;
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
据我了解,在构造函数之外编写它不会生成服务类HeroService 的实例,但为什么呢? (是 Angular 还是 TypeScript?)在这个例子中,Hero 也是一个类(虽然不是服务类,但在技术上仍然是一个类!),我们在构造函数之外声明了 heroes: Hero[] = [];,它可以工作.
【问题讨论】:
标签: angular typescript