0
0
NestJSframework~5 mins

Injectable decorator in NestJS

Choose your learning style9 modes available
Introduction

The @Injectable() decorator marks a class so NestJS can create and manage its instances automatically. It helps with sharing and reusing code easily.

When you want NestJS to create and manage a service or helper class for you.
When you need to inject a class into another class to share functionality.
When building modular code that is easy to test and maintain.
When you want to use dependency injection to keep your code clean and organized.
Syntax
NestJS
@Injectable()
export class ClassName {
  // class content
}

The decorator goes just above the class definition.

It tells NestJS this class can be injected as a dependency.

Examples
A simple service class that NestJS can inject elsewhere.
NestJS
@Injectable()
export class CatsService {
  getCats() {
    return ['Tom', 'Jerry'];
  }
}
Another injectable service with a different method.
NestJS
@Injectable()
export class DogsService {
  bark() {
    return 'Woof!';
  }
}
Sample Program

This example shows a simple GreetingService class marked with @Injectable(). It has a method to greet by name. The usage example creates an instance and prints a greeting.

NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class GreetingService {
  sayHello(name: string): string {
    return `Hello, ${name}!`;
  }
}

// Usage example (not part of NestJS app):
const service = new GreetingService();
console.log(service.sayHello('Friend'));
OutputSuccess
Important Notes

Always add @Injectable() to classes you want NestJS to manage.

Without it, NestJS cannot inject the class into other classes.

You can inject services into controllers or other services easily once they are injectable.

Summary

@Injectable() marks a class for NestJS dependency injection.

It helps create reusable and testable services.

Use it on any class you want NestJS to manage automatically.