0
0
NestJSframework~30 mins

Dependency injection basics in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Dependency injection basics
📖 Scenario: You are building a simple NestJS service that provides a greeting message. You want to use dependency injection to keep your code clean and testable.
🎯 Goal: Create a NestJS service called GreetingService that returns a greeting message. Then inject this service into a controller called GreetingController to return the greeting when a GET request is made.
📋 What You'll Learn
Create a service class named GreetingService with a method getGreeting() that returns the string 'Hello, NestJS!'.
Create a controller class named GreetingController.
Inject GreetingService into GreetingController using constructor injection.
Add a GET route /greet in GreetingController that returns the greeting from GreetingService.
💡 Why This Matters
🌍 Real World
Dependency injection helps keep code modular and testable by letting NestJS manage service creation and sharing.
💼 Career
Understanding dependency injection is essential for building scalable and maintainable backend applications with NestJS.
Progress0 / 4 steps
1
Create the GreetingService
Create a class called GreetingService with a method getGreeting() that returns the string 'Hello, NestJS!'.
NestJS
Need a hint?

Use the @Injectable() decorator to make the service injectable.

2
Create the GreetingController
Create a class called GreetingController and add the @Controller('greet') decorator to it.
NestJS
Need a hint?

Use the @Controller('greet') decorator to define the route prefix.

3
Inject GreetingService into GreetingController
Add a constructor to GreetingController that injects GreetingService as a private readonly property named greetingService.
NestJS
Need a hint?

Use constructor injection with private readonly greetingService: GreetingService.

4
Add GET route to return greeting
Add a method called getGreeting() in GreetingController decorated with @Get() that returns the result of this.greetingService.getGreeting().
NestJS
Need a hint?

Use the @Get() decorator to define the GET route handler.