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
What is tree-shakable about a service declared with `@Injectable({ providedIn: 'root' })`?
Answer: The service is excluded from the bundle if nothing in the app injects it
Because the provider registration lives on the service class itself rather than in an NgModule, bundlers can detect unused services and omit them from the output.
What happens when you use `useClass` in an Angular provider and specify a class different from the token?
Answer: Angular instantiates the specified class whenever the token is requested
useClass tells Angular to instantiate the given class when the provider token is resolved, enabling substitution of alternative implementations.
How can you inject a service only into a component's view children, not into projected ng-content children?
Answer: Use viewProviders: [] in the @Component decorator
viewProviders registers services that are only accessible inside the component's own template, invisible to content inserted via ng-content.
Which approach correctly provides an Angular service in a standalone component?
Answer: Add the service class to the standalone component's providers array
Standalone components support a providers array in @Component where you register services scoped to that component's injector.
What does the `multi: true` option in an Angular provider definition do?
Answer: Causes the token to resolve to an array containing all registered values for that token
When multi: true is set, Angular collects all providers registered under the same token into an array rather than overwriting each other.
What Angular token is used with `multi: true` to run initialization logic before the app bootstraps?
Answer: APP_INITIALIZER
APP_INITIALIZER accepts factory functions via multi: true; Angular awaits any returned Promises before rendering the first component.
In Angular, when is it appropriate to call `Injector.create()` to build a child injector manually?
Answer: When you need a scoped injector outside the normal component tree, such as in a dynamic component scenario
Injector.create() is used to build ad-hoc child injectors with custom providers, useful when dynamically creating components or services outside Angular's normal hierarchy.