Tips for building an effective delete function in Angular for eliminating a single record from a table

I've been working on creating a method to delete an employee by their ID, and I've tried various approaches in my VS Code. Unfortunately, all of them have resulted in errors except for this specific method. Whenever I click on the delete button, an error pops up on the console, and I'm not quite sure how to resolve it. Any help would be greatly appreciated:

employee-list.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { employee } from 'src/app/model/employee.model';
import { EmployeeService } from 'src/app/services/employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit{

  employees: employee[] = [];

  employeeName:string='';
  employeeNumber:Number=0;
  city:string=""; 
  postalCode:string="";
  state:string="";
  street:string="";
  
  constructor(private employeeService:EmployeeService,
    private http:HttpClient){}

  ngOnInit(): void {
    //add employee array

    this.GetAllEmployees();
  }

  GetAllEmployees():void{
    this.employeeService.GetAllEmployees().subscribe({
      next:(data)=>{
        this.employees=data;
        console.log(this.employees);
      }
    })
  }
  //DELETE METHOD:
  deleteEmployee(employeeId: number): void {
    if (employeeId !== null) {
      this.employeeService.deleteEmployee(employeeId).subscribe({
        next: () => {
          this.employees = this.employees.filter((emp) => emp.employeeId !== employeeId);
        },
        error: (error) => {
          console.log(error);
        }
      });
    }
  }
}

employee-list.component.html

 <h2>Emloyee List</h2>
<table class="table-stripad" >
<thead>
<tr>
  <th >Employee Name</th>
  <th >Phone Number</th>
  <th >Street</th>
  <th >City</th>
  <th >State</th>
  <th >Postal Code</th>
  <th>View</th>
  <th>Delete</th>
</tr>
</thead>
<tbody>
  <tr *ngFor="let employee of employees" class="active-row">
  <td>{{employee.employeeName}}</td>
  <td>{{employee?.employeeNumber}}</td>
  <td>{{employee.address?.city}}</td>
  <td>{{employee.address?.street}}</td>
  <td>{{employee.address?.state}}</td>
  <td>{{employee.address?.postalCode}}</td>
  <td>
    <a [routerLink]="['/employees',employee.employeeId]"> 
      <button (click)="(employee.employeeId)" class="btn"  >Detalis</button></a>
  </td>
  <td>
    <button *ngIf="employee.employeeId !== null" (click)="deleteEmployee(employee.employeeId!)" class="btn">Delete</button>
  </td>
  </tr> 
</tbody>
</table> 

employee.service.ts

//emp delete

deleteEmployee(employeeId:number | null): Observable<void> {
  const url = `${this.API_URL}/${employeeId}`;
  return this.http.delete<void>(url);}

Error message on the console

Error Message

endpoint in intelliJ

   @DeleteMapping("/employees/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteEmployee(@PathVariable Integer id){
        EmployeeService.deleteEmployee(id);
    }

Answer №1

The API request returned a status code of 404, indicating that the requested resource does not exist. Therefore, the endpoint http://localhost:8080/api/6 is not valid.

Based on the annotation

@DeleteMapping("/employees/{id}")
, the correct API endpoint should be
http://localhost:8080/employees/6
or possibly
http://localhost:8080/api/employees/6
if there is an additional @RequestMapping("/api") annotation in the backend controller.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

Issues with retrieving the scope attribute within a directive

I am currently facing an issue where I am unable to access the values stored in $scope.photoRes within my directive. When I use console.log(scope.photoRes) in the directive, it only displays an empty object. Here is the output from the console: Object {fi ...

Is Angular 2 built on Shadow DOM or Virtual DOM architecture?

When it comes to updating the DOM in Angular 2, does it utilize Shadow DOM or Virtual DOM? And did Angular 1 have a similar concept? ...

Tips for retrieving a string instead of an Observable in @angular/http

I'm currently integrating Angular 4 with .NET Core Web API. The Web API is providing a CustomerName as a string based on the Id given. Here is the service method in Angular 4. I know that angular/http needs to return an Observable due to it being an ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

Performance issues with the Django API causing significant delays in data retrieval

Currently, I am working on integrating Angular2 with Django (a Python framework). I have successfully created a basic API in Django that displays all the records from the database. You can access the API via the following link: [https://djangoshopnroar.he ...

Tips on preventing image previews from consuming too much text data while updating a database in Angular 12 using Material UI for image uploads within a FormGroup object

Currently working with Angular 12 and Angular Material for image uploads with preview. I have a formgroup object below, but I'm running into issues with the 197kb image preview text being inserted into the database. Despite trying setValue/patchValue/ ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

During the test, an unexpected error occurred: Configuration file error! Module 'karma-remap-istanbul' not found

Whenever I run ng test, I keep encountering the following error message - what could be causing this issue? An unhandled exception occurred: Error in configuration file! Error: Module 'karma-remap-istanbul' cannot be found Below is the content ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

Creating a personalized tooltip in Angular for a bubble chart with ApexCharts

I'm currently working on customizing the tooltip for a bubble chart using the ApexCharts library. Here is the link to my project. ...

This error message indicates that the certificate for Angular 13 has expired

After successfully installing Angular and verifying the version, I encountered an issue when attempting to run the command npm start. Despite multiple attempts at uninstalling and reinstalling everything, the problem persists. Running npm install also resu ...

Dynamic Dropdown Options in Angular 6 HTML Input Field

Looking to create an interactive HTML5 input field that guides the user with their input. Consider a scenario where the user is required to follow a specific grammar while entering text: rule: <expression> {<op><expression>} expression: ...

Guide on updating a table row upon clicking the edit button in an Angular 12 template-driven form

Currently, I have set up a table where the data can be edited by clicking on a hyperlink and then saving the changes with a button. The issue I am facing is that when I click on the edit link, all rows become editable instead of just the specific row I cli ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Error in ReactJS VSCode while integrating Cypress testing: The name 'cy' cannot be found

Currently working on a ReactJS Typescript project using NPM and VSCode. Despite all my Cypress tests running smoothly, I am encountering a syntax error in VSCode: Error: Cannot find name 'cy' Any ideas on how to resolve this issue? Attempted th ...

Using ngFor to iterate over a list of items in Angular and displaying them conditionally using ng

In the process of creating a template, I am faced with this challenge: <ul> <li *ngFor='let link of links'> <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container& ...

Error Alert: Accessing the 'email' property on the 'UserCredential' type in Angular and Firebase is not allowed

import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './../classes/user'; import { AlertService } from './alert.service'; import { Alert } from './../classes ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...