Bird
0
0

You want to maintain a single instance of a service shared across multiple lazy-loaded Angular modules. Which method ensures this singleton behavior?

hard📝 component behavior Q8 of 15
Angular - Services and Dependency Injection
You want to maintain a single instance of a service shared across multiple lazy-loaded Angular modules. Which method ensures this singleton behavior?
AAdd the service to the <code>providers</code> array of each lazy-loaded module
BProvide the service only in the root injector using <code>@Injectable({ providedIn: 'root' })</code>
CDeclare the service in each lazy-loaded module's component providers
DCreate a new instance manually in each lazy-loaded module
Step-by-Step Solution
Solution:
  1. Step 1: Understand lazy-loaded modules and injectors

    Lazy-loaded modules have their own injectors, so providing a service in them creates separate instances.
  2. Step 2: Use root injector for singleton

    Providing the service in the root injector ensures one instance shared across all modules, including lazy-loaded ones.
  3. Final Answer:

    Provide the service only in the root injector using @Injectable({ providedIn: 'root' }) -> Option B
  4. Quick Check:

    Root injector shares singleton across lazy modules [OK]
Quick Trick: Use providedIn root to share singleton in lazy modules [OK]
Common Mistakes:
MISTAKES
  • Providing service in lazy modules creates multiple instances
  • Assuming component providers share instances across modules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes