Menu
CoddyTech

Đăng ký nhà cung cấp

Thuộc phần TypeScript và NestJS trong hành trình Node.js của Coddy. Bài học 10 trên 24.

Nest chỉ tạo các lớp được liệt kê trong providers của module. Một provider có thể cần một provider khác, và bạn phải đăng ký tất cả các provider đó.

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

Nếu thiếu MailerService trong providers của module, ứng dụng sẽ không khởi động, và Nest sẽ cho biết chính xác thành phần không tìm thấy:

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

? đánh dấu đối số hàm khởi tạo còn thiếu, còn thông báo nêu tên lớp và module cần sửa.

challenge icon

Thử thách

Dễ
  • Bản khởi đầu thêm ClockService. Yêu cầu TasksService cung cấp dịch vụ này và thêm createdAt: this.clock.now() cho mỗi tác vụ mới.
  • Đăng ký ClockService trong TasksModule.
  • Gửi POST /tasks kèm theo một tiêu đề. Sau đó xóa ClockService khỏi providers, nhấn Chạy, đọc lỗi rồi thêm lại.

Tự làm thử

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);
    }
}

Tất cả bài học trong TypeScript và NestJS

Tự luyện tập: Playground Express