Performance: Service scope (root, module, component)
This affects initial load time and runtime memory usage by controlling service instance creation and reuse.
import { Injectable } from '@angular/core'; @Injectable() export class DataService { } // Provided in component decorator providers array
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { } // Used only in one component
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Service providedIn: 'root' | 0 (no DOM impact) | 0 | 0 | [OK] |
| Service provided in lazy module | 0 | 0 | 0 | [OK] Good |
| Service provided in component | 0 | 0 | 0 | [OK] Good |
providedIn property to 'root' mean in Angular?providedIn: 'root' meaningprovidedIn: 'module'. Instead, you add the service to the module's providers array.providers array scopes to component, @Injectable({ providedIn: 'module' }) is invalid syntax.providers array -> Option A@Component({
selector: 'app-example',
template: `{{counter}}
`,
providers: [CounterService]
})
export class ExampleComponent {
counter = 0;
constructor(private counterService: CounterService) {
this.counter = this.counterService.increment();
}
}app-example are rendered, what will be the value of counter in each?CounterService in providers inside the component creates a new instance per component.providers array. However, when injecting it in a lazy-loaded module, Angular throws an error that the service is not found. What is the likely cause?providers creates a new instance per component, isolating logs.root allows sharing common configuration across all logging instances.providers array and inject a global settings service from root. -> Option DPass the test and this pattern moves unknown