0
0
NestJSframework~5 mins

Service creation in NestJS

Choose your learning style9 modes available
Introduction

Services help organize your code by handling business logic separately from controllers. This keeps your app clean and easy to manage.

When you want to separate data handling from request handling in your app.
When you need to reuse logic across multiple parts of your application.
When you want to keep your controller code simple and focused on routing.
When you want to inject dependencies easily for testing or modularity.
Syntax
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  myMethod() {
    // business logic here
  }
}
Use the @Injectable() decorator to make the class available for dependency injection.
Services are usually plain classes with methods that contain your app's logic.
Examples
This service returns a simple greeting string.
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class GreetingService {
  getGreeting() {
    return 'Hello, world!';
  }
}
This service provides a method to add two numbers.
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class MathService {
  add(a: number, b: number): number {
    return a + b;
  }
}
Sample Program

This service defines a method to multiply two numbers. You can inject and use it in controllers or other services.

NestJS
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));
OutputSuccess
Important Notes

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.

Summary

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.