You must make the HeroService available to the dependency injection system before Angular can inject it into the HeroesComponent by registering a provider. A provider is something that can create or deliver a service; in this case, it instantiates the HeroService class to provide the service.
Provider负责实例化 service.
看这段TypeScript代码:
@Injectable({
providedIn: 'root',
})
When you provide the service at the root level, Angular creates a single, shared instance of HeroService and injects into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
一个最佳实践:
While you could call getHeroes() in the constructor, that’s not the best practice.
Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn’t do anything. It certainly shouldn’t call a function that makes HTTP requests to a remote server as a real data service would.
Instead, call getHeroes() inside the ngOnInit lifecycle hook and let Angular call ngOnInit() at an appropriate time after constructing a HeroesComponent instance.
尽量不要在构造函数里编写任何应用逻辑,而是把这些逻辑放到生命周期钩子 ngOnInit里。
在需要使用service 的Component里,首先import service的实现:
Angular Service依赖注入的一个具体例子
The parameter simultaneously defines a private heroService property and identifies it as a HeroService injection site.