我现在正在学习 Angular2 Heros 教程。
我具体是at this step :
Go back to the HeroesComponent and remove the HeroService from its providers array. We are promoting this service from the HeroesComponent to the AppComponent. We do not want two copies of this service at two different levels of our app.
app.comonent.ts:
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes.component';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<my-heroes></my-heroes>
`,
directives: [HeroesComponent],
providers: [
HeroService
]
})
export class AppComponent {
title = 'Main App';
}
heros.component.ts:
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
template: `
... bla bla bla ...
`,
styles:[`
... bla bla bla ...
`],
directives: [HeroDetailComponent],
providers: [
HeroService
]
})
export class HeroesComponent implements OnInit {
public heroes: Hero[];
selectedHero: Hero;
constructor(
private heroService: HeroService
){}
ngOnInit() {
this.heroService.getHeroes().then( heroes => this.heroes = heroes );
}
onSelect = function (hero: Hero){
this.selectedHero = hero;
}
}
我的问题是,当我从heros.components的Provider列表中删除HeroService时,为什么它仍然有效?
我的假设是,由于我们在构造函数中指定我们需要一个 HeroService,因此父组件(在本例中为 app.component)将提供一个 HeroService。这准确吗?
最佳答案
The providers array tells Angular to create a fresh instance of the HeroService when it creates a new AppComponent. The AppComponent can use that service to get heroes and so can every child component of its component tree.
所以你的假设部分正确。
实际上,您的 app.component
一旦被子组件注入(inject),就会创建您的服务的一个实例。由于您的 Hero.component 是 app.component 的子级,因此它将使用相同的实例。所以不是只是一个,而是唯一。
实际上,如果您多次实例化服务,了解该行为以避免错误很重要,这在大多数情况下可能不是您想要的。
<小时/>更新了更多信息:
正如 Mark Rajcok 在他的评论中正确指出的那样,一旦 app.component
的子组件之一注入(inject)该服务,该服务就会创建。如果没有子组件注入(inject)该服务,则不会创建该服务的实例。
正如 Ed Morales 所补充的,还有另一种可能性是通过使用 viewProviders
而不是 providers
来提供服务,这将使创建的实例只能由提供组件访问,而不是对于它的所有 child 。
关于Angular2 Heros 教程 - 子组件如何获取服务/提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737691/