Menu
CoddyTech

注册提供者

本课属于 Coddy Node.js 学习旅程的“TypeScript 和 NestJS”单元。第 10 课,共 24 课。

Nest 只会创建模块在 providers 中列出的类。一个提供者可以依赖另一个提供者,而每个提供者都必须注册。

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

如果模块的 providers 中缺少 MailerService,应用就无法启动,Nest 会准确指出它找不到什么:

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

? 标记缺失的构造函数参数,消息中还会指出需要修复的类和模块。

challenge icon

挑战

简单
  • 起始代码添加了 ClockService。在 TasksService 中注入它,并为每个新任务设置 createdAt: this.clock.now()。
  • 在 TasksModule 中注册 ClockService。
  • 发送带有标题的 POST /tasks 请求。然后从 providers 中移除 ClockService,点击“运行”,查看错误,再把它加回去。

亲手试试

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

TypeScript 和 NestJS中的所有课

自己练习: Express 在线编辑器