Bird
0
0

How should you provide UserService to achieve this?

hard🚀 Application Q15 of 15
Angular - Services and Dependency Injection
You want to inject a UserService into two standalone components, ProfileComponent and SettingsComponent, so they share the same instance of the service. How should you provide UserService to achieve this?
AUse <code>inject()</code> without providing UserService anywhere
BAdd UserService to the providers array of both components separately
CProvide UserService in the root injector using <code>@Injectable({ providedIn: 'root' })</code>
DCreate a new instance of UserService manually in each component
Step-by-Step Solution
Solution:
  1. Step 1: Understand service scope and sharing

    Providing a service in root makes Angular create one shared instance app-wide.
  2. Step 2: Compare with providing in components

    Providing in each component creates separate instances, so no sharing occurs.
  3. Final Answer:

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

    Root provider = shared singleton service [OK]
Quick Trick: Use providedIn: 'root' for shared singleton services [OK]
Common Mistakes:
MISTAKES
  • Providing service in each component causing multiple instances
  • Forgetting to provide service at all
  • Manually creating service instances instead of injecting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes