What is the best way to enhance the functionality to simultaneously update numerous records to json using Angular?

I'm working with Angular's HttpClient for CRUD operations. I have an edit option for each record, but I want to be able to update multiple records at once by selecting checkboxes and clicking the update button.

Could you please assist me in implementing this feature? I need to add a checkbox for each row so that users can select multiple records, then click on the edit button, select the updated option, and finally click the update button to apply changes to all selected records.

Additionally, it would be very helpful if I could get a count of how many records are applicable, not applicable, and FYI out of the total.

common.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor(private http:HttpClient) { }

  createUser(user: any) {
    return this.http.post("http://localhost:3000/users", user);
  }
  getAllUser() {
    return this.http.get("http://localhost:3000/users");
  }
  updateUser(user: any): Observable<any> {
    return this.http.put("http://localhost:3000/users/" + user.id, user);
  }
  deleteUser(user: any) {
    return this.http.delete("http://localhost:3000/users/" + user.id);
  }
}

app.component.ts

app.component.html

db.json

Answer №1

The issue lies within your batch update function. You are populating the batchUpdateUserList, but then sending the single record this.userObj to the server, which will not achieve the desired batch update.

  batchUpdateUser() {
    this.isBatchEdit = false;
    const batchUpdateUserList = []; // objects to 
    this.allUser.forEach(user => {
      if (user.checked) {
        user.impact = this.currentImpact
        batchUpdateUserList.push(user);
        user.checked = false;
      }
    });

    this.commonService.updateUser(this.userObj).subscribe(() => {
      this.getLatestUser();      
    }); 
  }

In my initial comment in the function, I mentioned the necessity of creating a new call to this.commonService.batchUpdate() for the server. However, if generating a new call that sends a list of users for update is not feasible, consider the following alternative:

  batchUpdateUser() {
    this.isBatchEdit = false;
    const batchUpdateUserList = []; // objects to 
    this.allUser.forEach(user => {
      if (user.checked) {
        user.impact = this.currentImpact
        batchUpdateUserList.push(user);
        user.checked = false;

        this.commonService.updateUser(user).subscribe();
      }
    });

    this.getLatestUser();   
  }

Although using this approach may be slow and unreliable for extensive updates, you can address this issue by employing forkJoin. Ideally, creating a new service specifically designed to send a list to the server for updating would be preferable. For an example, refer to the stackblitz; however, please note that the provided code has not been integrated with this solution due to the project's lack of connectivity to a server.

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

Using jQuery to Remove an Object or Array Easily

After making an ajax request, I received the following result: ["[1449270000000, 21]", "[1449356400000, 41]", [1449442800000, 60],... I am looking for a way to remove the quotation marks using jQuery. Despite trying multiple approaches, I have been uns ...

Retrieve list of friend names along with their corresponding friend IDs from MongoDB

Creating a MEAN app for the first time and successfully inserting users into MongoDB. Each user entry includes: { "name":"My Name", "country":"Italy", "friends":"5922c66b4e708e27a02b7937" } First query: How can I manually add multiple friends (separate t ...

Creating a personalized fake database functionality in Angular

Is there a way to implement the fake-db feature in Angular while utilizing this resource? I need it to support an API response structure like the one below for list retrieval. // GET 'api/outlets' { data: [ {'id':1, 'name&ap ...

What is the best way to navigate between multiple pages in an Angular 7 application using ngIf?

In my Angular 7 app, I am facing an issue with switching between three different pages. While I have managed to switch between two of them successfully, the messages page loads in the documents section whenever I click on it. Even though I have attempted ...

Error encountered with Retrofit while attempting to retrieve a boolean value that is false

When working with retrofit 2.0 and using OkHttp3 as the network layer, I encountered an issue where Retrofit would throw an error when the web server sent boolean data with a false value. For example, if the web service JSON looked like {"login":false}, ...

Setting up an auto-complete dropdown with PrimeNG and Angular

Struggling with the auto-complete feature, where the dropdown loads initially but fails to filter values as I type. Here's a snippet from service.ts: getUserLocations(UserID: string, allList:string ) { return this._http.get(environment.BASE ...

What's the best way to generate JSON output in Ruby on Rails?

I attempted the following approach to handle AJAX and it was successful (in HAML): - response.content_type = "application/json" = render :text => array_data.to_json however, when I tried: - response.content_type = "application/json" = render ...

Upon upgrading to Angular 8, the function this._delegate.setNgStyle is not recognized

Following the update of my project from Angular 7 to Angular 8 and resolving all errors caused by breaking changes, I am encountering a new issue: <div fxFill ngStyle.xs="overflow:auto"> This line is resulting in the following error: ERROR Type ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

"Encountering issues with the functionality of two Angular5 routers

main.component.html [...] <a routerLink="/company-list">Open</a> [...] <main> <router-outlet name="content"><router-outlet> </main> [...] app.compoment.html <router-outlet><router-outlet> app.routing.modu ...

I'm facing an issue with using JSON as an attribute in Sequelize with Postgres

I am trying to retrieve data from a table based on JSON criteria. var jsondata="{'job_media','job_quote','job_invoice', 'job_client', 'created_by', 'job_status', 'job_source', 'job ...

What is the best method to export all information from an Elastic Search Index to a JSON-formatted file, ensuring that the _id field

As a newcomer to both Spark and Scala, my goal is to extract all data from a specific index in Elastic Search and load it into an RDD to then write it to Mongo DB. After loading the Elastic search data into an esJsonRDD, I noticed that the RDD contents ar ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Ways to decline requests using interceptors depending on the content of the request?

Is there a way to achieve a status of 200 and stop the controller call if a certain key in the request payload meets my criteria? I've implemented Interceptors in my application, but I'm struggling to send a status of "200" without causing an ex ...

"Troubleshooting: Vue JS Axios Post Request Not Passing Data to PHP Server

After successfully uploading an image in Vue JS and sending a POST request to a Laravel Route, the JSON response from the API is displayed on the client side as expected. However, there seems to be an issue with retrieving this response in PHP, as it retur ...

Troubleshooting: @HostListener for window scroll event not functioning as expected

Having trouble creating a sticky header that stays fixed when scrolling down in an Angular 4 application. The scroll event is not being detected. The header is located in the layout component, while the content I want to be scrollable is placed in the rou ...

Ways to describe an item using a mix of determined and undetermined attributes

I am attempting to create a TypeScript type that includes properties I know and properties I do not know. Here is what I have tried: type MetaType = { res?: HttpResponse; req?: HttpRequest; [key: string]: string | number | boolean | string[] } ...

The Angular application is not displaying correctly on mobile devices due to a lack

Having an issue with my angular build. I've deployed my website at this link: It appears fine when viewed on a desktop and even in the devtools. However, when I try to access it on my phone, the layout looks terrible! Any suggestions on how to fix ...

Converting a JSON array with two dimensions to PHP

My JSON encoded array originated from a 2D PHP string array and appears as follows: [ [ "a1", "a2", "a3", "a4" ], [ "b1", "b2", "b3", "b4" ], [ "c1", "c2", "c3", "c4" ] ] The validity of this array has been ...

The eslint command encounters an issue on the CI Server, displaying the error message "ESLint is unable to locate the 'standard' config to extend from."

My local eslint configuration works perfectly fine with vscode editor, but I'm encountering an issue on the CI Server. When running the linting command, I receive the following error: eslint:config-array-factory Config file found: /home/worker/worksp ...