Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular httpclient delete example

Suggested Videos
Part 67 - Handling angular resolver errors | Text | Slides
Part 68 - Angular httpclient post example | Text | Slides
Part 69 - Angular httpclient put example | Text | Slides

In this video we will discuss deleting data on the server using Angular HttpClient service.


To issue a DELETE request, we use HttpClient service delete() method.


In employee.service.ts file, include the following deleteEmployee() method

baseUrl = 'http://localhost:3000/employees';

deleteEmployee(id: number): Observable<void> {
    return this.httpClient.delete<void>(`${this.baseUrl}/${id}`)
        .pipe(catchError(this.handleError));
}

Code Explanation:
  • deleteEmployee() method takes the ID of the employee to delete as a parameter
  • delete() method does not return anything so we have set the return type to void
  • The URL that is passed as a parameter to the HttpClient delete() method has the ID of the employee to delete
Delete button click event handler is in DisplayEmployeeComponent. So modify deleteEmployee() method in display-employee.component.ts file as shown below.

deleteEmployee() {
  this._employeeService.deleteEmployee(this.employee.id).subscribe(
    () => console.log(`Employee with ID = ${this.employee.id} Deleted`),
    (err) => console.log(err)
  );
  this.notifyDelete.emit(this.employee.id);
}

The success callback function logs the ID of the deleted employee to the console and the error callback function logs the error to the console.

angular crud tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources