Services help organize your code by handling business logic separately from controllers. This keeps your app clean and easy to manage.
Service creation in NestJS
import { Injectable } from '@nestjs/common'; @Injectable() export class MyService { myMethod() { // business logic here } }
import { Injectable } from '@nestjs/common'; @Injectable() export class GreetingService { getGreeting() { return 'Hello, world!'; } }
import { Injectable } from '@nestjs/common'; @Injectable() export class MathService { add(a: number, b: number): number { return a + b; } }
This service defines a method to multiply two numbers. You can inject and use it in controllers or other services.
import { Injectable } from '@nestjs/common'; @Injectable() export class CalculatorService { multiply(a: number, b: number): number { return a * b; } } // Usage example (in a controller or another service): // const calculator = new CalculatorService(); // console.log(calculator.multiply(3, 4));
Always decorate your service class with @Injectable() so NestJS can manage it.
Services can be injected into controllers or other services via constructor injection.
Keep services focused on business logic, not on handling HTTP requests directly.
Services hold your app's business logic separately from controllers.
Use @Injectable() to make services injectable and reusable.
Inject services into controllers to keep code clean and modular.
Practice
What is the main purpose of creating a service in a NestJS application?
Solution
Step 1: Understand the role of services in NestJS
Services are designed to contain business logic, keeping controllers clean and focused on handling requests.Step 2: Differentiate services from controllers and other parts
Controllers handle HTTP requests, schemas define data structure, and styling is unrelated to services.Final Answer:
To hold the business logic separate from controllers -> Option DQuick Check:
Service purpose = business logic separation [OK]
- Confusing services with controllers
- Thinking services handle HTTP requests
- Assuming services define database schemas
Which decorator is used to make a class injectable as a service in NestJS?
Solution
Step 1: Identify the decorator for service injection
In NestJS,@Injectable()marks a class as a provider that can be injected.Step 2: Differentiate from other decorators
@Controller()is for controllers,@Module()for modules, and@Service()does not exist in NestJS.Final Answer:
@Injectable() -> Option AQuick Check:
Service decorator = @Injectable() [OK]
- Using @Controller() instead of @Injectable()
- Confusing @Module() with service decorator
- Assuming @Service() exists in NestJS
Given the following service code, what will be the output when getHello() is called?
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
getHello(): string {
return 'Hello, NestJS!';
}
}Solution
Step 1: Analyze the getHello method
The method returns the string 'Hello, NestJS!'.Step 2: Determine the output of calling getHello()
CallinggetHello()returns exactly the string defined, no errors or undefined.Final Answer:
"Hello, NestJS!" -> Option AQuick Check:
Method return = "Hello, NestJS!" [OK]
- Assuming method returns undefined
- Confusing output with error messages
- Mixing up string content
Identify the error in this service code snippet:
import { Injectable } from '@nestjs/common';
@Injectable()
export class MathService {
add(a: number, b: number) {
return a + b
}
}Solution
Step 1: Check syntax correctness
The methodaddcorrectly takes two numbers and returns their sum. Semicolons are optional in TypeScript.Step 2: Verify method declaration and return type
Return type annotation is optional; TypeScript infers it. Parentheses are present and correct.Final Answer:
No error, code is correct -> Option CQuick Check:
Code syntax = correct [OK]
- Thinking semicolons are mandatory
- Expecting explicit return type always
- Misreading method syntax
You want to create a service that provides a list of users and inject it into a controller. Which of the following is the correct way to create and inject the service?
1. Create service with @Injectable()
2. Define a methodgetUsers()returning an array
3. Inject service in controller constructor
4. Use service method inside controller method
Solution
Step 1: Create service with @Injectable()
This decorator makes the service injectable and reusable.Step 2: Inject service via constructor parameter in controller
Constructor injection is the NestJS standard for dependency injection.Step 3: Use service methods inside controller methods
This keeps code modular and clean.Final Answer:
Create service with @Injectable(), inject via constructor parameter -> Option BQuick Check:
Service injection = @Injectable() + constructor [OK]
- Omitting @Injectable() on service
- Using @Controller() on service
- Injecting service incorrectly with property decorators
Ready to prove it?
Pass the test and this pattern moves unknown
