0
0
Angularframework~15 mins

@Injectable decorator and providedIn in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Injectable Decorator with providedIn in Angular
📖 Scenario: You are building a simple Angular service to share a message across components in a small app.
🎯 Goal: Create an Angular service using the @Injectable decorator with providedIn to make it available app-wide.
📋 What You'll Learn
Create a service class named MessageService
Use the @Injectable decorator with providedIn: 'root'
Add a public string property message with the value 'Hello from MessageService'
Export the service class
💡 Why This Matters
🌍 Real World
Angular services are used to share data and logic across components without repeating code.
💼 Career
Understanding @Injectable and providedIn is essential for creating efficient, maintainable Angular applications and is a common task in Angular developer roles.
Progress0 / 4 steps
1
Create the MessageService class
Create a class named MessageService and export it.
Angular
Need a hint?

Use export class MessageService {} to create and export the class.

2
Add the @Injectable decorator with providedIn
Add the @Injectable decorator above the MessageService class with providedIn: 'root' inside it. Also, import Injectable from @angular/core.
Angular
Need a hint?

Use @Injectable({ providedIn: 'root' }) to make the service available app-wide.

3
Add a public message property
Inside the MessageService class, add a public string property named message and set it to 'Hello from MessageService'.
Angular
Need a hint?

Declare public message: string = 'Hello from MessageService'; inside the class.

4
Complete the service export
Ensure the MessageService class is exported and decorated with @Injectable with providedIn: 'root', and has the public message property.
Angular
Need a hint?

Check that the service is fully defined with the decorator, export, and property.