0
0
Angularframework~3 mins

Why @Injectable decorator and providedIn in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple decorator can save you from messy, repeated code and make your app smarter!

The Scenario

Imagine you have a service in your Angular app that you want to share across many components. Without a clear way to tell Angular how to create and share this service, you end up manually creating instances everywhere.

The Problem

Manually creating service instances leads to duplicated code, inconsistent data, and makes your app harder to maintain. It's like making a new coffee pot for every cup instead of sharing one pot.

The Solution

The @Injectable decorator with providedIn tells Angular to create and share a single instance of the service automatically. This makes your app cleaner and more efficient.

Before vs After
Before
const service = new MyService(); // created in every component
After
@Injectable({ providedIn: 'root' })
export class MyService {} // Angular shares one instance
What It Enables

This lets Angular manage service creation and sharing, so your app stays organized and fast without extra code.

Real Life Example

Think of a music app where the playlist service is shared across screens. Using @Injectable with providedIn means all parts of the app see the same playlist without extra setup.

Key Takeaways

@Injectable marks a class as a service Angular can create.

providedIn tells Angular where to provide the service (like 'root' for app-wide).

This avoids manual service creation and keeps your app clean and efficient.