Add Task Service
- Implement task management
Create methods to handle task operations in the service.
- Manage task state
Learn how to maintain and update task data in the service.
- Handle task operations
Implement methods for adding, updating, and removing tasks.
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.
-
Update the file
src/app/task-service.ts
.task-service.ts import { Injectable } from "@angular/core";import { Task } from "./models/task.model";@Injectable({providedIn: "root",})export class TaskService {tasks: WritableSignal<Task[]> = signal([{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: Partial<Task>): void {this.tasks.update(tasks => [...tasks,{...task,id: uuid(),createdAt: new Date(),}]);}} -
Let’s adapt model in order to be able to handle eventual empty values coming from the form
src/app/task.model.ts
.task.model.ts export interface Task {id: string;title?: string | null;description?: string | null;createdAt: Date;}
The function `addTasks’ will be called from your TaskFormComponent and add a new task to the existing list of tasks.
Partial<Task>
:It allows the task parameter to include only some properties of the Task interface, making them optional.
...
(spread operator):...tasks
: Copies all existing tasks into a new array....task
: Copies all properties of the provided task object into the new task.
- The function
uuid()
:Generates a unique id and sets the createdAt property to the current date before adding the new task to the list.
You have created a function in the TaskService service to isolate the task addition logic.