Skip to content

Delete a Task with HTTP Client

Chapter Objectives
  • Delete a task using HTTP Client

    Delete a task from the list by making an API call to the mock server.

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(id: string) {
return this.http.delete<Task>(`http://localhost:3000/tasks/${id}`);
}
  1. Update the task-service.ts file.

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

Update TaskForm 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:

  1. Update the src/app/task-list/task-list.ts file.

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

document.location.reload(); This is not best practice, but for simplicity we reload the page. In best practice, you would update the local state (signal or component data) by filtering out the deleted task from the current tasks array, avoiding the need to reload the entire page and providing a better user experience.

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

What you've learned

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