NG.IV · Angular 22 practice question
A developer is building a layered data access system where `BasicDataStore` relies on `AdvancedDataStore` to fetch supplemental data. How does the provided pattern ensure that `BasicDataStore` receives an instance of `AdvancedDataStore` when it is constructed?
import {inject, Service} from '@angular/core';
import {AdvancedDataStore} from './advanced-data-store';
@Service()
export class BasicDataStore {
private advancedDataStore = inject(AdvancedDataStore);
private data: string[] = [];
addData(item: string): void {
this.data.push(item);
}
getData(): string[] {
return [...this.data, ...this.advancedDataStore.getData()];
}
}
Check answer and explanation
Correct answer: The `inject(AdvancedDataStore)` call within the class body automatically resolves and provides the necessary dependency instance.
Explanation
The mechanism employed utilizes the `inject(AdvancedDataStore)` invocation inside the class body to automatically obtain and supply the required dependency instance. This illustrates the contemporary approach to resolving dependencies without relying on a constructor.
Common trap
The description stating that the dependency must be explicitly passed into the constructor of `BasicDataStore` describes a different pattern, namely traditional constructor injection, which is not the technique demonstrated. Furthermore, the assertion that the `@Service()` decorator alone handles the location and instantiation of `AdvancedDataStore` is inaccurate.
Source: Angular docs: Creating and using services — Injecting into another service
Checked against the cited text on 2026-11-25.