0
0
Angularframework~30 mins

Why services are needed in Angular - See It in Action

Choose your learning style9 modes available
Why services are needed
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the component selectors as HTML tags inside the app component template.