[Angular] Component's dependency injection
An Angular service registered on the NgModule is globally visible on the entire application. Moreover it is a singleton instance, so every component that requires it via its constructor, will get the same instance. However this is not always the desired behavior.
Rather you may like to get a fresh instance of a given service every time a component requests it. This is especially powerful for caching scenarios for instance. In this lesson we will learn how to achieve such behavior with Angular’s hierarchical dependency injector.
It menas that, when you provide dependency injection for a component, it comes and goes with Component, which also mean, everytime component is renewed, the service provides init value, the old value will lose.
@Component({ selector: 'app-child', template: ` <h3>Child component</h3> <pre>{{ personService.getPerson() | json }}</pre> <app-person-edit></app-person-edit> `, providers: [PersonService] })
import { Injectable } from '@angular/core'; @Injectable() export class PersonService { name = 'Joe'; getPerson() { return { name: this.name, age: 23 }; } setPersonName(value) { this.name = value; } }
So everytime the component's will get serivce name as 'Joe'.
相关文章
- 一个 Angular 开发人员对腾讯 Cloud Studio 使用后的体验报告
- angular debounce throttle「建议收藏」
- Angular 面试题汇总2-Component/Service (Angular v8+)
- Angular 14 inject 函数使用过程中的一些注意事项
- orbital angular momentum_omnidirectional
- Angular 应用里 index.html 的作用
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- Angular SSR 应用启动时的一些保护措施
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular与React、Vue.js的对比
- 高质量 VR 直播有望了,Google 带来 Equi-Angular Cubemaps 技术