프로바이더 등록
Coddy Node.js 여정의 TypeScript와 NestJS 섹션에 포함된 레슨. 17개 중 7번째.
Nest는 모듈이 providers에 나열한 클래스만 생성합니다. 프로바이더는 다른 프로바이더를 요청할 수 있으며, 모든 프로바이더를 등록해야 합니다.
@Injectable()
export class OrdersService {
constructor(private readonly mailer: MailerService) {}
}MailerService가 모듈의 providers에 없으면 앱이 시작되지 않고, 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.?는 누락된 생성자 인수를 표시하며, 메시지에는 수정해야 할 클래스와 모듈의 이름이 나옵니다.
챌린지
쉬움- 시작 코드에
ClockService가 추가되어 있습니다.TasksService에서 이를 요청하고 새 작업마다createdAt: this.clock.now()를 지정하세요. TasksModule에ClockService를 등록하세요.- 제목과 함께
POST /tasks를 전송하세요. 그런 다음providers에서ClockService를 빼고, Run을 누른 뒤 오류를 확인하고 다시 추가하세요.
직접 해보기
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);
}
}