Sub topic 3
Scoping Services to a Component Subtree
This chapter assumes you already know @Injectable, inject(), provider recipes, and the injector hierarchy from earlier chapters.
Component-Scoped Services
When you list a service in a component's providers array, each instance of that component gets its own copy of the service. Its descendants share that copy. viewProviders works the same way, except that content projected through <ng-content> cannot see the service.
import { Component, Injectable, inject } from '@angular/core';
@Injectable()
export class FormDraftService {
value = '';
}
@Component({
selector: 'app-editor',
standalone: true,
providers: [FormDraftService],
template: `<input [value]="draft.value" (input)="draft.value = $any($event.target).value" />`
})
export class EditorComponent {
protected readonly draft = inject(FormDraftService);
private readonly parentDraft = inject(FormDraftService, { skipSelf: true, optional: true });
}Sharing State
A root service holds app-wide state. A component-scoped service holds state for one subtree. You can store that state in a signal or in an RxJS BehaviorSubject. Keep the writable part private and expose only read-only views. A common mistake is to mutate the array inside a signal in place, which does not notify consumers. Replace it with update(list => [...list, item]) instead.
Resolution Modifiers
| Option | Effect |
|---|---|
| `optional` | Returns `null` instead of throwing |
| `self` | Looks only in the current injector |
| `skipSelf` | Starts the lookup at the parent |
| `host` | Stops the lookup at the host component |
Multi Providers and Injection Context
When you set multi: true, Angular collects every value registered for a token into an array:
import { EnvironmentInjector, InjectionToken, inject, runInInjectionContext } from '@angular/core';
export const PLUGINS = new InjectionToken<string[]>('PLUGINS');
export const pluginProviders = [
{ provide: PLUGINS, useValue: 'audit', multi: true },
{ provide: PLUGINS, useValue: 'metrics', multi: true }
];
export function loadPlugins(injector: EnvironmentInjector): string[] {
return runInInjectionContext(injector, () => inject(PLUGINS));
}You can call inject() only during construction: in field initializers, in constructors, inside factory providers, and in route guards. If you call it later, for example in ngOnInit or in a setTimeout callback, it throws NG0203. In those places, wrap the call in runInInjectionContext and pass it an injector.
Testing with TestBed
TestBed lets you swap a real dependency for a test double, an object that stands in for the real service, by passing { provide: CartService, useValue: fakeCart } in providers. To replace a component-scoped provider, use TestBed.overrideComponent. Root-level overrides do not reach providers declared on the component.
Exercise
Two sibling EditorComponents each list FormDraftService in providers. What does parentDraft hold in each, if no ancestor provides the service?
Show answer
null in both. skipSelf skips the component's own injector, no ancestor provides the service, and optional turns the error into null.
Exercise
Why does calling inject(PLUGINS) inside ngOnInit fail, and how do you fix it?
Show answer
ngOnInit runs outside an injection context, so inject() throws NG0203. Inject the value in a field initializer, or wrap the call in runInInjectionContext with an injector.