Passing Selected Table Row Model Data to Backend in Angular 7

My goal is to send the selected data in a table row, which I select through a checkbox, to the server. However, I'm unsure about how to handle this via a service call. While I have the basic structure in place, I need assistance with sending the items for a delete REST API call. The server endpoint for this service call is a C# .Net Core JSON.

CustomComponent.ts

@Component({
  templateUrl: 'CustomComponent.html'
})
export class CustomComponent implements OnInit, OnDestroy {

  // User Fields
  currentUser: User;
  users: User[] = [];
  currentUserSubscription: Subscription;

  loading : boolean;
  // Action Fields
  viewData: any;
  viewName: string;
  refNumber: number;
  currentActionSubscription: Subscription;
  displayedColumns: string[] = [];
  dataSource: any = new MatTableDataSource([]);
  pageSizeOptions: number[] = [10, 20, 50];

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  selection = new SelectionModel<TableRow>(true, []);

  defaultSort: MatSortable = {
    id: 'defColumnName',
    start: 'asc',
    disableClear: true
  };

  ...

}

Answer №1

Two essential tasks need to be addressed in your current code:

  1. You must send the ids of the selected rows back to the server, usually done through the URL in a DELETE request.
  2. You need to subscribe to the observable to materialize it. The HTTP request won't execute without any subscribers. Ideally, the component should make a service call like this:
this.actionService.deleteRow(this.selection).subscribe((response) => {
  console.log('Success!');
});

Update:

Regarding task number 1, the implementation will depend on how your server method is set up. If it requires an array of numeric IDs, the view.service.ts may resemble the following:

deleteRow(selection: SelectionModel<TableRow>): Observable<{}> {
  console.log('testing service');
  // create an array of query parameters using the property that identifies a table row
  const queryParams = selection.selected.map(row => `id=${row.id}`);
  // include the query parameters in the URL
  const url = `http://localhost:15217/actions/deleteRow?${queryParams.join('&')}`;
  return this.http.delete<any>(url);
}

I'm making assumptions about how you send information about table rows to your server. If you're still facing challenges, provide more details about the DELETE endpoint.

Update 2:

With better insight into the object structure...

deleteRow(selection: SelectionModel<TableRow>): Observable<{}> {
  console.log('testing service');
  // create an array of query parameters using the property that identifies a table row
  const queryParams = [...selection._selection].map(row => `id=${row.id}`);
  // include the query parameters in the URL
  const url = `http://localhost:15217/actions/deleteRow?${queryParams.join('&')}`;
  return this.http.delete<any>(url);
}

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

utilizing parent scope in a jQuery function callback

Currently, I am facing an issue concerning a jQuery callback working on a variable that is outside of its scope. To illustrate this problem, consider the code snippet below: $('#myBtn').on('click', function(e) { var num = 1; / ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

Ways to fix the perpetual cycle in adal-angular4 following authentication redirect

I have been working on an Angular 8 application that utilizes Microsoft Azure Active Directory authentication with adal-angular4. I've successfully set up an ASP.NET Core API linked to a client app on Azure. To configure Active Directory, I referred ...

Is there a way to determine the number of clicks on something?

I'm attempting to track the number of times a click event occurs. What is the best method to achieve this? There are two elements present on the page and I need to monitor clicks on both of them. The pseudo-code I have in mind looks something like ...

Ways to modify, delete, or insert data elements within a collection of values using React

I'm currently working on implementing a dropdown menu for departments within a location edit form. I'm wondering if there's a way to update or create new elements in the list of values. The API I'm using only sends specific data elemen ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

What causes certain webpack / Babel ES6 imports without a specified extension to resolve as "undefined"?

When I try to import certain ES6 files (such as .js, .jsx, .ts, .tsx) using the syntax import ComponentName from './folder/ComponentName'; (without extension), they end up resolving as undefined. This occurs even though there are no errors from W ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

My backend axios post request is not returning any data to my external API. What could be the issue?

I've encountered an issue where I'm attempting to transmit data from my client-side using an ajax call to my backend axios post request, which is responsible for posting data to an external API URL. Despite receiving a 200 status code, none of th ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Angular 2 cleaning up subscriptions when view is destroyed

I've developed an interesting "appService" that serves as the intermediary between all my components, handling interactions like forms and navigations. This service boasts multiple event emitters to which various components subscribe for different pu ...

determining the properties of a given data type

I am currently working with a type that I have obtained from a third party source. My goal is to determine the type of a specific property within that type, using TypeScript. For example: type GivenType = { prop: string; } type desiredType = <&l ...

Is it permissible to use Aloha editor GPL v.2 on a business website?

While researching the licensing of Aloha Editor, I came across some confusing information. I found a reference to another editor under LGPL: However, I couldn't find a clear answer on whether I can use Aloha JS code on a commercial website with GPL v ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

The synchronization of template stamping with the connectedCallback function

Issue Explanation It appears that there is a timing discrepancy with Polymer (2.x) when querying for nodes contained within a template element immediately after the connectedCallback() function has been executed. Ideally, the initial call of this.shadowRo ...

Ways to retrieve the locale parameter from the URL in Next Js

For my Next Js application, I've successfully implemented multi language support using the next-i18next module. Everything is working smoothly. Below is the code for my NabBar component: const NavBar = ({...props}) => { const router = useRouter( ...

I attempted to access data from the phpmyadmin database, but the browser is displaying an error message stating "cannot get/employee", while there are no errors showing in the command prompt

const { json } = require('express/lib/response'); const mysql=require ('mysql'); const express=require('express'); var app=express(); const bodyparser=require('body-parser'); app.use(bodyparser.json()); var mysq ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Steps for inserting an item into a div container

I've been attempting to create a website that randomly selects elements from input fields. Since I don't have a set number of inputs, I wanted to include a button that could generate inputs automatically. However, I am encountering an issue where ...