Menu
CoddyTech

Registrare i provider

Fa parte della sezione TypeScript e NestJS del percorso Node.js di Coddy. Lezione 7 di 17.

Nest crea solo le classi che un modulo elenca in providers. Un provider può richiedere un altro provider e ognuno di essi deve essere registrato.

@Injectable()
export class OrdersService {
    constructor(private readonly mailer: MailerService) {}
}

Se MailerService manca da providers del modulo, l'app non si avvia e Nest indica esattamente cosa non è riuscito a trovare:

Nest can't resolve dependencies of the OrdersService (?).
Please make sure that the argument MailerService at index [0]
is available in the OrdersModule module.

? indica l'argomento mancante del costruttore e il messaggio specifica la classe e il modulo da correggere.

challenge icon

Sfida

Facile
  • Il progetto iniziale aggiunge ClockService. Richiedilo in TasksService e assegna a ogni nuova attività createdAt: this.clock.now().
  • Registra ClockService in TasksModule.
  • Invia POST /tasks con un titolo. Poi rimuovi ClockService da providers, premi Run, leggi l'errore e aggiungilo di nuovo.

Provalo tu

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

export interface Task {
    id: number;
    title: string;
    done: boolean;
    createdAt?: string;
}

@Injectable()
export class TasksService {
    private tasks: Task[] = [
        { id: 1, title: 'Write the README', done: true, createdAt: '2026-01-05T09:00:00.000Z' },
        { id: 2, title: 'Fix the login bug', done: false, createdAt: '2026-01-06T14:30:00.000Z' },
        { id: 3, title: 'Plan the sprint', done: false, createdAt: '2026-01-07T08:15:00.000Z' },
    ];

    findAll(done?: string): Task[] {
        if (done === undefined) {
            return this.tasks;
        }
        return this.tasks.filter((task) => task.done === (done === 'true'));
    }

    findOne(id: number): Task {
        const task = this.tasks.find((task) => task.id === id);
        if (!task) {
            throw new NotFoundException(`Task ${id} not found`);
        }
        return task;
    }

    create(title: string): Task {
        const id = Math.max(0, ...this.tasks.map((task) => task.id)) + 1;
        const task = { id, title, done: false };
        this.tasks.push(task);
        return task;
    }

    remove(id: number): void {
        this.findOne(id);
        this.tasks = this.tasks.filter((task) => task.id !== id);
    }
}

Tutte le lezioni di TypeScript e NestJS