Bird
Raised Fist0
NestJSframework~10 mins

Injectable decorator in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Injectable decorator
Define class
↓
Add @Injectable decorator
↓
NestJS registers class as provider
↓
Class can be injected into constructors
↓
NestJS creates instance when needed
↓
Use instance in dependent classes
Shows how adding @Injectable marks a class for NestJS to manage and inject where needed.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  getCats() { return ['Tom', 'Jerry']; }
}
Defines a service class marked with @Injectable so NestJS can inject it.
Execution Table
StepActionEvaluationResult
1Read class CatsServiceClass definedClass CatsService created
2Apply @Injectable decoratorDecorator marks classClass registered as provider
3NestJS scans providersFinds CatsServiceCatsService added to DI container
4Another class requests CatsServiceConstructor injectionNestJS creates CatsService instance
5Call getCats()Method runsReturns ['Tom', 'Jerry']
6End of flowNo more actionsExecution stops
💡 All steps complete; class is injectable and usable via NestJS DI
Variable Tracker
VariableStartAfter Step 2After Step 4Final
CatsServiceundefinedRegistered as providerInstance createdInstance used
Key Moments - 2 Insights
Why do we need the @Injectable decorator on a class?
Without @Injectable, NestJS does not register the class as a provider, so it cannot inject it. See execution_table step 2 where the decorator marks the class.
What happens when another class requests CatsService in its constructor?
NestJS looks up CatsService in its container and creates an instance to inject. See execution_table step 4 for this injection process.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 3?
AAnother class requests CatsService
BCatsService method getCats() is called
CNestJS registers CatsService as a provider
DThe class CatsService is defined
💡 Hint
Check the 'Action' and 'Result' columns at step 3 in the execution_table
At which step does NestJS create an instance of CatsService?
AStep 4
BStep 5
CStep 2
DStep 1
💡 Hint
Look for 'Instance created' in the 'Result' column in execution_table
If we remove @Injectable decorator, which step would fail?
AStep 1
BStep 3
CStep 2
DStep 5
💡 Hint
Without @Injectable, NestJS cannot register the class as provider (step 3)
Concept Snapshot
@Injectable decorator marks a class as a provider
NestJS registers it in the dependency injection container
Allows class instances to be injected into constructors
Enables reuse and easy testing
Without it, injection fails
Use on services, repositories, and providers
Full Transcript
The @Injectable decorator in NestJS marks a class so the framework knows to manage it as a provider. When NestJS starts, it scans for classes with @Injectable and registers them in its dependency injection container. Later, when another class needs this provider, NestJS creates an instance and injects it automatically. This process allows easy sharing and reuse of services. Without @Injectable, NestJS will not recognize the class for injection, causing errors. The execution flow starts with defining the class, applying the decorator, registering the provider, injecting the instance, and finally using the class methods.

Practice

(1/5)
1. What is the main purpose of the @Injectable() decorator in NestJS?
easy
A. To style components with CSS
B. To define a route handler in a controller
C. To create a database connection automatically
D. To mark a class so NestJS can manage it for dependency injection

Solution

  1. Step 1: Understand the role of @Injectable()

    This decorator tells NestJS that the class can be injected as a dependency, making it reusable and manageable by the framework.
  2. Step 2: Differentiate from other decorators

    Other decorators like @Controller() or database decorators serve different purposes, not dependency injection.
  3. Final Answer:

    To mark a class so NestJS can manage it for dependency injection -> Option D
  4. Quick Check:

    @Injectable() = marks class for DI [OK]
Hint: Remember: @Injectable() means NestJS manages the class [OK]
Common Mistakes:
  • Confusing @Injectable() with @Controller()
  • Thinking it creates routes or database connections
  • Assuming it styles components
2. Which of the following is the correct syntax to make a service class injectable in NestJS?
easy
A. function Injectable() { return class MyService {} }
B. class MyService {}
C. @Injectable() class MyService {}
D. @Injectable class MyService {}

Solution

  1. Step 1: Recall correct decorator syntax

    In NestJS, decorators are functions called with parentheses, so @Injectable() is correct.
  2. Step 2: Check each option

    class MyService {} lacks the decorator. function Injectable() { return class MyService {} } is invalid syntax. @Injectable class MyService {} misses parentheses after @Injectable.
  3. Final Answer:

    @Injectable() class MyService {} -> Option C
  4. Quick Check:

    Decorator syntax requires parentheses () [OK]
Hint: Always use parentheses with decorators like @Injectable() [OK]
Common Mistakes:
  • Omitting parentheses after @Injectable
  • Trying to use @Injectable without decorator syntax
  • Confusing class and function syntax
3. Given the following code, what will be the output when appService.getMessage() is called?
import { Injectable } from '@nestjs/common';

@Injectable()
class AppService {
  getMessage() {
    return 'Hello from AppService';
  }
}

const appService = new AppService();
console.log(appService.getMessage());
medium
A. Hello from AppService
B. undefined
C. Error: AppService is not injectable
D. null

Solution

  1. Step 1: Understand @Injectable() effect on class instantiation

    The @Injectable() decorator marks the class for NestJS DI but does not change normal instantiation behavior.
  2. Step 2: Analyze the code execution

    The code creates an instance manually and calls getMessage(), which returns the string as expected.
  3. Final Answer:

    Hello from AppService -> Option A
  4. Quick Check:

    Manual instantiation still works; method returns string [OK]
Hint: Manual new works; decorator doesn't block normal class use [OK]
Common Mistakes:
  • Assuming decorator breaks manual instantiation
  • Expecting an error without NestJS container
  • Thinking method returns undefined
4. Identify the error in this NestJS service code:
import { Injectable } from '@nestjs/common';

@Injectable
export class UserService {
  getUser() {
    return 'User data';
  }
}
medium
A. Missing parentheses after @Injectable decorator
B. Class name should be lowercase
C. Method getUser must be async
D. Missing export keyword

Solution

  1. Step 1: Check decorator syntax

    The @Injectable decorator must be called with parentheses: @Injectable().
  2. Step 2: Verify other code parts

    Class name casing is correct by convention. Method need not be async. Export keyword is present.
  3. Final Answer:

    Missing parentheses after @Injectable decorator -> Option A
  4. Quick Check:

    Decorator requires () to work properly [OK]
Hint: Always add () after decorators like @Injectable() [OK]
Common Mistakes:
  • Forgetting parentheses after decorator
  • Thinking method must be async
  • Confusing export keyword presence
5. You want to create a reusable logging service in NestJS that other services can inject. Which of the following is the best way to define it?
hard
A. Create a class without @Injectable() and instantiate it manually everywhere
B. Use @Injectable() on the logging class and inject it where needed
C. Define logging functions in a plain JavaScript object and export it
D. Use @Controller() decorator on the logging class

Solution

  1. Step 1: Understand dependency injection benefits

    Using @Injectable() allows NestJS to manage the logging service lifecycle and inject it automatically where needed.
  2. Step 2: Evaluate options for reusability and testability

    Manual instantiation loses DI benefits. Plain objects lack lifecycle and DI. @Controller() is for routing, not services.
  3. Final Answer:

    Use @Injectable() on the logging class and inject it where needed -> Option B
  4. Quick Check:

    Injectable services = reusable and testable [OK]
Hint: Always use @Injectable() for reusable NestJS services [OK]
Common Mistakes:
  • Skipping @Injectable() and instantiating manually
  • Using @Controller() for services
  • Using plain objects without DI benefits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard