Lesson 7 / 33

Providers & Services

Services encapsulate business logic; providers are registered in modules.

Anatomy of a service

A service is a class with @Injectable() that holds your business logic—fetching data, validating rules, etc.

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [];

  findAll() {
    return this.users;
  }

  create(user) {
    this.users.push(user);
    return user;
  }
}

Providers in modules

Register services in the providers array of a module; also export them if other modules need them.