0
0
AngularConceptBeginner · 3 min read

What is Injectable Decorator in Angular: Simple Explanation

The @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.

typescript
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();
  }
}
Output
<h1>Hello from GreetingService!</h1>
🎯

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.

Key Takeaways

The @Injectable decorator makes a class injectable by Angular's dependency system.
It allows Angular to create and share one instance of the service across the app.
Use it for services that provide data or logic to multiple components.
Adding providedIn: 'root' makes the service a singleton available everywhere.
It helps keep your app modular, testable, and easy to maintain.