Discover how a simple decorator can save you from messy, repeated code and make your app smarter!
Why @Injectable decorator and providedIn in Angular? - Purpose & Use Cases
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.
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 @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.
const service = new MyService(); // created in every component@Injectable({ providedIn: 'root' })
export class MyService {} // Angular shares one instanceThis lets Angular manage service creation and sharing, so your app stays organized and fast without extra code.
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.
@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.