What is Injectable Decorator in Angular: Simple Explanation
@Injectable decorator in Angular marks a class as available for dependency injection, letting Angular create and share instances of that class. It tells Angular that this class can be injected into constructors of other classes to provide services or data.How It Works
Think of the @Injectable decorator as a label on a service class that says, "Hey Angular, you can create and share this for me." When Angular sees this label, it knows it can make an instance of the class and give it to other parts of your app that ask for it.
This works like a vending machine: you put in a request (ask for a service), and Angular gives you the item (an instance of the class). The decorator helps Angular understand which classes it can manage and supply automatically.
Example
This example shows a simple service class marked with @Injectable. Angular can then inject this service into a component to use its data.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class GreetingService { getGreeting() { return 'Hello from GreetingService!'; } } import { Component } from '@angular/core'; import { GreetingService } from './greeting.service'; @Component({ selector: 'app-root', template: '<h1>{{ greeting }}</h1>' }) export class AppComponent { greeting: string; constructor(private greetingService: GreetingService) { this.greeting = this.greetingService.getGreeting(); } }
When to Use
Use the @Injectable decorator when you want Angular to manage a class as a service that can be shared across components or other services. This is common for data fetching, logging, or business logic that many parts of your app need.
For example, if you have a user authentication service or a data API service, marking it with @Injectable lets Angular provide the same instance wherever needed, keeping your app organized and efficient.
Key Points
- @Injectable marks a class as available for Angular's dependency injection system.
- It allows Angular to create and share instances of the class automatically.
- Use
providedIn: 'root'to make the service a singleton available app-wide. - It helps keep your code modular and easy to test.