LABS
COOKIES

Delete a Task with HTTP Client

Git diff Code changes
Chapter Objectives
  • Delete a task using HTTP Client

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

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}}`);
}
  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:

  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've learned

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