您必须仅在相关组件中提供服务,然后它仅可用于该特定组件及其子组件。如果您在模块中使用了该服务,则它在应用程序的根级别中可用。
@Component({
selector: 'app-villains-list',
templateUrl: './villains-list.component.html',
providers: [ VillainsService ]
})
Run Code Online (Sandbox Code Playgroud)
通过在 VillainsListComponent 元数据中而不在其他地方提供 VillainsService,该服务仅在 VillainsListComponent 及其子组件树中可用。VillainService 是一个关于 VillainsListComponent 的单例,因为它是在那里声明的。只要VillainsListComponent 没有被销毁,它就会是VillainService 的同一个实例,但是如果有多个VillainsListComponent 实例,那么VillainsListComponent 的每个实例都会有自己的VillainService 实例。
https://angular.io/guide/hierarchical-dependency-injection
| 归档时间: |
|
| 查看次数: |
3302 次 |
| 最近记录: |