Skip to content

Add a task via the service

Chapter Objectives

  • ✔️
    Create a function in `TaskService`
    Create a method that adds a new task to the `TaskService` based on the task object passed as a parameter.

Design a method to add a task

The TaskService will be responsible for managing the task list as planned. Create a function to add a task to the list.

🎓 Instructions

  1. Modify the file src/app/task.service.ts.

    task.service.ts
    import { Injectable } from "@angular/core";
    import { Task } from "./models/task.model";
    import { TaskForm } from "./models/task.model";
    @Injectable({
    providedIn: "root",
    })
    export class TaskService {
    tasks: Task[] = [
    {
    id: uuid(),
    title: "Task 1",
    description: "Description of task 1",
    createdAt: new Date(),
    },
    {
    id: uuid(),
    title: "Task 2",
    description: "Description of task 2",
    createdAt: new Date(),
    },
    ];
    addTask(task: TaskForm): void {
    this.tasks.push({
    ...task,
    id: uuid(),
    createdAt: new Date(),
    });
    }
    }

This new function will be called from your TaskFormComponent component to add a new task to the list.

✔️ What you have learned

You have created a function in the TaskService service to isolate the task addition logic.