Bird
0
0

You want to share user login status across multiple components using a singleton service. Which approach correctly ensures the service is singleton and updates are reflected everywhere?

hard🚀 Application Q15 of 15
Angular - Services and Dependency Injection
You want to share user login status across multiple components using a singleton service. Which approach correctly ensures the service is singleton and updates are reflected everywhere?
ACreate service with <code>@Injectable({ providedIn: 'root' })</code> and use a BehaviorSubject to hold login status.
BCreate service without providedIn and add it to each component's providers array.
CCreate service with <code>@Injectable({ providedIn: 'root' })</code> but store login status in a local variable inside each component.
DCreate service with <code>@Injectable()</code> and manually instantiate it in each component constructor.
Step-by-Step Solution
Solution:
  1. Step 1: Ensure singleton service provision

    Using providedIn: 'root' makes the service singleton app-wide.
  2. Step 2: Use BehaviorSubject for reactive shared state

    BehaviorSubject allows components to subscribe and get updates when login status changes.
  3. Step 3: Evaluate other options

    Options B, C, and D break singleton or do not share state properly.
  4. Final Answer:

    Create service with @Injectable({ providedIn: 'root' }) and use a BehaviorSubject to hold login status. -> Option A
  5. Quick Check:

    Singleton + reactive state = shared updates [OK]
Quick Trick: Use providedIn: 'root' and BehaviorSubject for shared reactive state [OK]
Common Mistakes:
MISTAKES
  • Adding service to component providers breaking singleton
  • Storing shared data only inside components
  • Manually creating service instances instead of DI

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes