When sending a delete request to the Spring server, Angular does not reveal the list

I sent a simple request to the server to remove the item

staff.component.ts

delete(staff: Staff, index: number) {
    if (staff.id != null) {
      this.staffService.delete(staff.id)
        .subscribe(() => {
          this.staffList.splice(index, 1);
        });
    }
 }

staff.service.ts

delete(id: number): Observable<any> {
  const urlDelete:string = this.SERVER_API + id;
  return this.http.delete<Staff>(urlDelete, this.httpOptions);
}

After deletion, there is an update on the server, but the list in staff.component.ts only refreshes twice. How can I ensure that the list is immediately updated after clicking the delete button?

employee.component.html

<tr *ngFor="let staff of staffList; let i = index">
    <td>{{staff.name}}</td>
    <td>{{staff.surname}}</td>
    <td>{{staff.email}}</td>
    <td>{{staff.salary}}</td>
    <td>{{staff.department}}</td>
    <td>
      <span class="btn btn-outline-primary" routerLink="get-staff/{{staff.id}}">View</span>
    </td>
    <td>
      <span class="btn btn-outline-primary" routerLink="update-staff/{{staff.id}}">Update</span>
    </td>
    <td>
      <form (submit)="delete(staff, i)">
        <button class="btn btn-outline-primary" type="submit">Delete</button>
      </form>
    </td>
</tr>

After deletion, there is an update on the server, but the list in staff.component.ts only refreshes twice. How can I ensure that the list is immediately updated after clicking the delete button?

Answer №1

In order to make sure that the employee list is promptly updated after deleting an item, my recommendation is to enhance the delete() function by incorporating a call to the method responsible for fetching the most recent list of employees from the server:

deleteEmployee(employee: Employee, index: number): void {
  if (employee.id != null) {
    this.employeeService.deleteEmployee(employee.id)
      .pipe(
        tap(() => this.employees.splice(index, 1)),
        switchMap(() => this.employeeService.fetchEmployees())
      )
      .subscribe();
  }
}

Verify if your component contains a fetchEmployees() method that retrieves the employee list. If it doesn't exist, you should create one:

fetchEmployees(): Observable<any> {
  return this.employeeService.fetchEmployees()
    .pipe(
        tap(employees => this.employees = employees)
     );
}

By following these steps, each time an employee is deleted from the list, the changes will be instantly reflected, enabling you to stay updated on any modifications made.

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

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

The resolution of a promise occurs upon the invocation of a function

I have a component A that has the capability to display an image: <img *ngIf="displayImgService.showImage" (click)="displayImgService.hideImage()" src="..."> Additionally, I've developed a service called manageImgS ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

Angular 6 - accepting an HTTP GET request as the app loads

Upon the initial startup of my Angular application, just before its pages are loaded onto the user's browser, I aim to retrieve certain information from the HTTP request that triggered the app's launch. More precisely, I am looking to obtain the ...

Developing a TypeScript Library from Scratch

After following the instructions on this particular website, I have implemented the following JavaScript code: function A(id) { var about = { Version: "0.0.0.1", }; if (id) { if (window === this) { return new A(i ...

Attempting to receive an HTTP response using HTTPS and basic authentication, but receiving an "Unauthorized" error

I am encountering an issue while utilizing this particular API. My aim is to retrieve a JSON object through a GET method over https. Strangely, the output displays "HTTP/1.1 401 Unauthorized" despite having correct user credentials. Can someone please advi ...

Add a pair of icons into the JTextpane

Is there a way to insert multiple images into a JTextPane? I am currently facing an issue where only the first image is being appended with my code. Image img = null; Image img2 = null; try { img = ImageIO.read(new File(Main.imagePath + "1.jpg")); ...

Does Java truly conform to the principles of OOP if it still includes primitive data types?

It's a common saying that everything in Java is an object. But what about primitive data types? ...

Tailwind CSS styling appears to be malfunctioning in the production build of Next.js, despite functioning correctly in the

Despite following the proper build process with npm run build + npm run start, my Tailwind styling is not functioning correctly in the production build. Oddly enough, when I use npm run dev, the styling works as expected and my page displays with a purple ...

How to Send a Push Notification from an ASP.NET Application to an Android App

I have been trying to send a small Push Notification from my ASP.NET WEB API Post Method to my Simple Android App, and I have tried several methods and conducted research on this topic. Currently, I am utilizing the Google Cloud Messaging Service to deliv ...

When the imagepath in an Angular application is not updated, it will revert to null

Below is the code snippet that I am currently working on: <div class="col-sm-4 pl-5"> <img attr.src="{{item?.imagePath}}" required height="200" width="200"> </div> In my TypeScript file (ts), I have the following function: editBlog ...

Tips on maintaining a constant number of elements displayed within a container while scrolling using *ngFor

In an effort to improve the performance of loading a large amount of data inside a container div, I implemented a solution. It initially worked fine, but as I continued to append elements to the list while scrolling down, it started to slow down significan ...

The Angular2 app and NodeJs in the Docker container are unresponsive

After creating a new Angular2 app using angular-cli and running it in Docker, I encountered an issue where I could not connect to it from localhost. First, I initialized the app on my local machine: ng new project && cd project && "put m ...

"Trouble accessing the URL" error encountered when trying to load templateUrl for dynamic components in Angular 2

Attempted to modify a solution found here. The modification works well, but when changing the template to templateUrl in the component that needs to be loaded dynamically, an error occurs: "No ResourceLoader implementation has been provided. Can't rea ...

Why aren't images displaying on my JPanel?

I've been struggling to display both the squares I generated in the program and the imported ImageIcon on my JPanel. Despite spending a considerable amount of time on this, I'm still unable to resolve the issue and enable movement for the player ...

What is the best way to "connect" an interface in TypeScript?

I'm working on creating a child interface that mirrors the structure of a base interface. Any tips on how to achieve this? interface BaseInterface { api: { [key: string]: string }; ui: { [key: string]: string }; } interface ChildInterface { / ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...