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: `Child component
{ { personService.getPerson() | json }}`, 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'.