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

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

Tips on making Angular Material form controls dynamic

I am currently facing a dilemma where I am unsure how to dynamically set form controls. Below is the code snippet that illustrates my issue: <div [formGroup]="form"> <mat-form-field appearance="legacy"> <input matI ...

Angular: verifying the presence of any of the ng-content slots supplied

I have a component template that contains several ng-content elements: <div class="form__general"> <ng-content select="[general]"></ng-content> </div> <div class="form__footer"> <ng-conte ...

Utilizing Angular and TypeScript: The best approach for managing this situation

I need some guidance on handling asynchronous calls in Angular. Currently, I am invoking two methods from a service in a controller to fetch an object called "categoryInfo." How can I ensure that these methods return the categoryInfo correctly and displa ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...

Developing applications with Angular 4 and AppInventor window

Currently, I have a local Angular 4 application that utilizes localStorage on a desktop browser for data persistence. Within the application, I have implemented a WebViewer in AI. It is clear that localStorage cannot function in AI2, so alternative data s ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Using TypeScript in .cshtml Razor Files

Recently, I embarked on a new project utilizing the ASP.NET-MVC framework. For this particular project, I decided to opt for TypeScript over JavaScript. While Visual Studio provides excellent support for TypeScript, I encountered some compatibility issues ...

Angular 6 secure access control

To prevent unauthorized access, if a user is not logged in and attempts to access a secure URL, they should be redirected to the login page. Even if the URL is directly entered in the browser's address bar. I came across a solution on this website th ...

Angular Material Drop Down menu with UI-Router Integration

When the user clicks on the person icon, it triggers a form (form.html) using the ui-router logic defined in app.js. There are two types of dropdown boxes - one using the select tag and the other using the md-select tag. Everything works fine until I click ...

Using Angular2 and Typescript to declare a variable of type "any" can result

Hello StackOverflow community, I am encountering an issue with my JavaScript code where a global variable is sometimes not defined. I have a configuration class in Angular2 that imports this global variable using 'declare var any'. Within the cl ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

Can you guide me on utilizing the drag and drop functionality in Angular 8 CDK to merge two cards together?

My current challenge involves attempting to drag one card over another card in order to effectively "merge" or "combine" them, similar to the action of dragging an image onto a folder on a desktop. Despite utilizing HTML5 native drag and drop functionalit ...

Angular 5 Web-Based EPUB Reader

Just getting started with Angular 5 and I'm looking to display an epub file on a page without resorting to iframes. Any suggestions on how to achieve this? ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...