Delete information based on its unique identifier

Currently, I am trying to remove data from a list but encountering a small issue with the following code.

Component Code

removeSelectedRows(){
    console.log(this.selection.selected.map(item => item.userId))
    const selectedRowIds = this.selection.selected.map(item => item.userId);
       console.log(selectedRowIds)
      this.UserService.deleteUser(selectedRowIds).subscribe(res =>{
        this.dataSource.data = this.dataSource.data.filter(data => data.userId !== selectedRowIds);
      }, err =>{
        console.error(err);  
      }, ()=>{
        // this.clearUserForm();
        this.loadUsers(this.pageIndex);
      });
  }

The error arises from this section of the code

this.UserService.deleteUser(selectedRowIds).subscribe(res =>{
            this.dataSource.data = this.dataSource.data.filter(data => data.userId !== selectedRowIds)
.

selectRowIds causing an error

Argument of type 'string[]' is not assignable to parameter of type 'string'

Answer №1

selectedRowIds is actually an array, so comparing a string with an array of strings wouldn't work. You might want to consider using the Array.includes() method instead.

this.dataSource.data.filter(data => !selectedRowIds.includes(data.userId))

I hope this explanation clarifies things for you.


Update

This is based on an assumption since the actual workings of the deleteUser method are unknown. It appears that the service's method expects a single user ID. Therefore, you may need to either iterate over the selected IDs or modify the service method to handle an array of IDs. However, be cautious as making multiple separate API calls can lead to unexpected results.

selectedRowIds.forEach((selectedID) => {

    this.UserService.deleteUser(selectedID).subscribe(res =>{
    //                            ^^ Only one ID is passed here

        this.dataSource.data = this.dataSource.data.filter(data => data.userId !== selectedID);
    //                                                                 ^^^^^^^^^^^^^^^^ Filtering by selectedID
      }, err =>{
        console.error(err);  
      }, ()=>{
        // this.clearUserForm();
        this.loadUsers(this.pageIndex);
      }
    );
});

However, I do not recommend this approach due to potential multiple API calls being made (if applicable).

Answer №2

After much searching, I have finally discovered the solution to my issue

Component Code

selectedRow: any;

removeSelectedRows(){
    console.log(this.selectedRow.userId)
       this.UserService.deleteUser(this.selectedRow.userId).subscribe(res =>{
        this.dataSource.data = this.dataSource.data.filter(data => data.userId!== this.selectedRow.userId);
      }, err =>{
        console.error(err);  
      }, ()=>{
        this.ngOnInit();
        this.loadUsers(this.pageIndex);
      });
  }

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

What is the best way to ensure that an animation has finished before moving on to the next route?

I attempted a solution from this source, but unfortunately, it did not work for me. What I tried to do was incorporate the code from this example into my application. However, the challenge I faced was transitioning from the /login route to the /home rout ...

The object must contain a property 'children', which is required in the type '{ children: any; }' but missing in the type '{}'

While learning React from a variety of sources, I've encountered an issue with one of the examples. Error message: Property 'children' is missing in type '{}' but required in type '{ children: any; }' export default fu ...

Is it possible in Firebase to retrieve multiple queries and consolidate them into a collectionData?

In situations where the number of equalities exceeds 10, the "in" operator can be utilized. In such cases, the array can be divided into multiple sub-arrays of size 10 and multiple query requests can be initialized. When the array length is less ...

When the button is clicked, I desire to reveal the background color of a specific div

<div class="mat-list-item" *ngIf="authService.isAdmin()" (click)="openModal('site-settings', site.siteID)"> <span class="mat-list-item-content">{{ "Application.site_settings_label&q ...

How can one effectively monitor the advancement of a file transfer operation?

Looking at integrating a Spring Boot REST API with an Angular Frontend, I am interested in monitoring file upload/download progress. I recently came across an informative article that dives into the implementation details of this feature. The approach see ...

What is the method for including a placeholder (instead of a label) in the MUI 5 DatePicker component?

I'm looking to customize the placeholder text in MUI 5's date picker. You can find the MUI 5 datepickerlink here: https://mui.com/x/react-date-pickers/date-picker/ The desired outcome:: I've tried referring to this chat, but it hasn't ...

Exploring the customization options for Prime NG components is a great way to

Currently, I am working on a project that involves utilizing Prime NG components. Unfortunately, the p-steps component does not meet one of our requirements. I am looking to customize the Prime NG p-steps component to fit our needs. Is there a way to cre ...

Creating type definitions for recursive functions in TypeScript

I've created a JavaScript function that continuously accepts functions(params => string) until it receives an object, at which point it resolves the final string as a concatenation of all the functions invoked over the same object passed in at the ...

Yes, indeed - Entering the schema of a retrieved field from an Object schema

After deciding to upgrade from Yup version 0.29 to 1.2, I encountered some challenges with its types. Seeking assistance in finding the best solution for typing yup schemas. In version 0.29, the universal type Schema fit everywhere, but now it no longer d ...

Managing clearing values/strings for different input types like text/password upon form submission in Angular2

Here is a code snippet for an HTML form: <div> <form class="form-horizontal" role="form" (ngSubmit)="createUser(Username.value, Password.value)"> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <input type="text" class=" ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

How can the carousel item numbers be adjusted for proper display?

I'm currently working on an Angular app and have encountered a task related to displaying 5 cards using mdbootstrap. I want to showcase these cards in a carousel format, but with a twist - I only want the carousel functionality to be active on mobile ...

When utilizing Next.js with TypeScript, you may encounter an error message stating that the property 'className' is not found on the type 'IntrinsicAttributes & IntrinsicClassAttributes'

I recently put together a basic nextjs app using typescript. Here's the link to the example: https://github.com/zeit/next.js/tree/master/examples/with-typescript However, I encountered an issue where I am unable to add the className attribute to any ...

Select one of 2 parameters and begin typing

I recently encountered a situation where I needed to define a type with an id field (string) and an oldId field (number), but I wanted these fields to be exclusive. For example: { id: "1234", name: "foo" } { oldId: 1234, name: "b ...

Collaborative React front end elements are now housed in their own TypeScript project within Visual Studio 2017

In Visual Studio, our project structure includes the following: PublicClient, Admin, and SharedComponents. The SharedComponents project is essential because many components are shared between our client and admin interface. This structure is based on the f ...

Setting up Angular Universal on an already existing Angular 2 application with the help of the CLI

Encountering obstacles while trying to integrate the universal CLI into an existing Angular 2 application by following the guidelines provided in this link: During the initial command to install angular-universal: npm install body-parser angular2-univers ...

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Is there another option for addressing this issue - A function that does not declare a type of 'void' or 'any' must have a return value?

When using Observable to retrieve data from Http endpoints, I encountered an error message stating that "A function whose declared type is neither 'void' nor 'any' must return a value." The issue arises when I add a return statement in ...

In Angular 11, the error message "Type 'Object' cannot be assigned to type 'NgIterable<any> | null | undefined'" is appearing

Struggling to grasp the concepts of Angular and TypeScript for the first time, particularly puzzled by why this code snippet is not considered valid! http.service.ts export class HttpService { constructor(private http: HttpClient) { } getBeer() { ...