📖 Scenario: You are building a simple Angular app that shows user information on multiple components. You want to share the same user data between these components without repeating code or creating confusion.
🎯 Goal: Build an Angular service to hold user data and use it in two components to display the same information.
📋 What You'll Learn
Create a service to store user data
Create two components that use the service to get user data
Show the user name in both components
Use Angular dependency injection to provide the service
💡 Why This Matters
🌍 Real World
Sharing user data or settings across multiple parts of an app without duplicating code.
💼 Career
Understanding services and dependency injection is essential for building scalable Angular applications.
Progress0 / 4 steps
1
Create the user data service
Create an Angular service called UserService with a public property userName set to the string 'Alice'.
Angular
Hint
Use @Injectable decorator with providedIn: 'root' to make the service available app-wide.
2
Create the first component using the service
Create an Angular component called FirstComponent that injects UserService in its constructor and has a public property userName set to the service's userName. Display {{ userName }} in the component template.
Angular
Hint
Inject the service in the constructor and assign userName from the service.
3
Create the second component using the service
Create an Angular component called SecondComponent that injects UserService in its constructor and has a public property userName set to the service's userName. Display {{ userName }} in the component template.
Angular
Hint
Repeat the same pattern as FirstComponent to use the service in SecondComponent.
4
Use both components in the app template
Add the selectors <app-first></app-first> and <app-second></app-second> inside the main app component template to show both components on the page.
Angular
Hint
Use the component selectors as HTML tags inside the app component template.
Practice
(1/5)
1. Why do Angular apps use services instead of putting all code inside components?
easy
A. To make components load slower
B. To share data and logic across components easily
C. To avoid using TypeScript
D. To write more HTML code
Solution
Step 1: Understand the role of services
Services hold shared data and logic that multiple components can use.
Step 2: Compare with components
Components focus on showing the UI, not on sharing data or logic.
Final Answer:
To share data and logic across components easily -> Option B
Quick Check:
Services share data and logic = A [OK]
Hint: Services share logic, components show UI [OK]
Common Mistakes:
Thinking services slow down the app
Believing services replace HTML
Confusing services with components
2. Which is the correct way to inject a service into an Angular component constructor?