Skip to content

Modify task deletion with HTTP Client

Chapter Objectives

  • ✔️
    Delete a task with HTTP Client
    Learn how to delete a task from the list using HTTP Client in an Angular application.

TaskService

Based on the HTTP protocol, you will use the delete function to remove a task from the list: http.delete(). This function expects only one parameter, the URL of the resource to delete, including the id of the task to remove.

deleteTask(task: Task) {
return this.http.delete<Task>(`${http://localhost:3000/tasks/${task.id}}`);
}

🎓 Instructions

  1. Modify the task.service.ts file.

    import { Injectable } from "@angular/core";
    import { HttpClient } from "@angular/common/http";
    import { Task, TaskForm } from "./task.model";
    @Injectable({
    providedIn: "root",
    })
    export class TaskService {
    constructor(private http: HttpClient) {}
    deleteTask(id: string) {
    return this.http.delete<Task>(`http://localhost:3000/tasks/${id}`);
    }
    }

TaskFormComponent

Update TaskFormComponent to use this new function. The simplest way to do this would be to apply the same logic as in the previous lesson, updating the submit function to make an API call and navigate to the list page. This would result in the following code:

🎓 Instructions

  1. Modify the src/app/task-list/task-list.component.ts file.

    import { Component } from "@angular/core";
    import { TaskService } from "../task.service";
    @Component({
    selector: "app-task-list",
    templateUrl: "./task-list.component.html",
    styleUrls: ["./task-list.component.css"],
    })
    export class TaskListComponent {
    tasks$ = this.taskService.getTasks();
    constructor(private taskService: TaskService) {}
    deleteTask(id: string): void {
    this.taskService.deleteTask(id).subscribe(() => {
    document.location.reload();
    });
    }
    }

Following the same logic seen previously, we will wait for the request response to refresh the task list view.

✔️ What you have learned

You have learned how to send a DELETE request with HttpClient to delete a task in an Angular application.