0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use @Injectable Decorator in NestJS: Simple Guide

In NestJS, use the @Injectable decorator to mark a class as a provider that can be injected into other classes via dependency injection. This decorator tells NestJS to manage the class lifecycle and make it available for injection in constructors.
๐Ÿ“

Syntax

The @Injectable decorator is placed above a class declaration to mark it as a provider. This allows NestJS to create and inject instances of this class where needed.

  • @Injectable(): Marks the class as injectable.
  • Class declaration: The service or provider class you want to inject.
typescript
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  // service methods and properties
}
๐Ÿ’ป

Example

This example shows a simple service class marked with @Injectable and how it is injected into a controller using constructor injection.

typescript
import { Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
export class GreetingService {
  getGreeting(): string {
    return 'Hello from GreetingService!';
  }
}

@Controller()
export class AppController {
  constructor(private readonly greetingService: GreetingService) {}

  @Get()
  getHello(): string {
    return this.greetingService.getGreeting();
  }
}
Output
When you visit the root URL, the response will be: "Hello from GreetingService!"
โš ๏ธ

Common Pitfalls

Common mistakes when using @Injectable include:

  • Forgetting to add @Injectable() on the service class, which causes NestJS to throw an error when injecting.
  • Not registering the provider in a module's providers array, so NestJS doesn't know about it.
  • Trying to inject a class that is not decorated with @Injectable or not provided in any module.
typescript
/* Wrong: Missing @Injectable decorator */
export class WrongService {}

/* Right: Add @Injectable decorator */
import { Injectable } from '@nestjs/common';

@Injectable()
export class RightService {}
๐Ÿ“Š

Quick Reference

Remember these tips when using @Injectable in NestJS:

  • Always decorate service classes with @Injectable().
  • Register providers in the module's providers array.
  • Use constructor injection to access services.
  • @Injectable enables NestJS to manage the class lifecycle and dependencies.
โœ…

Key Takeaways

Use @Injectable() to mark classes as providers for dependency injection in NestJS.
Always register injectable classes in a module's providers array.
Inject services via constructor parameters to use them in other classes.
Forgetting @Injectable or module registration causes injection errors.
The decorator enables NestJS to manage service lifecycles automatically.