Services & Dependency Injection Flashcards
7 cards from real Angular Web Framework practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Services & Dependency Injection flashcards as text
Which Angular decorator marks a class as available to the DI system as a provider?
Answer: @Injectable
@Injectable marks a class so Angular's DI system knows it can be injected and, if needed, also inject its own dependencies.
What does the `providedIn: 'root'` option inside @Injectable do?
Answer: Creates a singleton instance available application-wide via the root injector
providedIn: 'root' registers the service with the root injector, producing a single shared instance across the entire app and enabling tree-shaking.
How do you inject a service into an Angular component using the modern inject() function (Angular 14+)?
Answer: private service = inject(MyService);
The inject() function, called in an injection context (constructor or field initializer), retrieves the service from the current injector without constructor parameter syntax.
What is the purpose of the `@Inject()` decorator on a constructor parameter?
Answer: It specifies an injection token when the dependency type alone is insufficient
@Inject(TOKEN) explicitly tells Angular which DI token to use for that parameter, commonly used with InjectionToken values.
Which provider syntax uses an existing service instance to satisfy a different token?
Answer: { provide: X, useExisting: Y }
useExisting creates an alias so that token X resolves to the same instance already registered under token Y.
In a lazy-loaded module, where is a service provided if it is listed in that module's `providers` array?
Answer: A child injector created specifically for that lazy module
Lazy-loaded modules get their own child injector, so services provided there are isolated to that module and not shared with the rest of the application.
What Angular CLI command generates a new service named `data` in a `services` folder?
Answer: ng generate service services/data
ng generate service services/data creates data.service.ts and its spec file inside the services/ directory.