Передача строки таблицы выбора модели на сервер в Angular 7 - PullRequest
0 голосов
/ 07 февраля 2020

Я пытаюсь отправить выбранные данные в строке таблицы, которые я выбираю, с помощью флажка на сервер, но у меня есть вопросы о том, как их следует отправлять через службу. У меня есть скелет basi c, но мне нужна помощь с получением элементов для вызова API удаления REST. Использование C#. Net Core JSON вызова в качестве конечной точки сервера для этого сервисного вызова.

view.component.ts

    @Component({
  templateUrl: 'view.component.html'
})
export class ViewComponent 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
  };

  defaultPaginator: MatPaginator;

  constructor(
    private iconRegistry: MatIconRegistry,
    private sanitizer: DomSanitizer,
    private actionService: ActionService
  ) {
    this.loading = false;
    this.iconRegistry.addSvgIcon(
      'thumbs-up',
      this.sanitizer.bypassSecurityTrustResourceUrl(
        'assets/img/examples/thumbup-icon.svg'
      )
    );
  }

  loadAction(action: any) {

    this.loading = true;
    // If there is already data loaded into the View, cache it in the service.
    if (this.viewData) {
      this.cacheAction();
    }

    if (this.sort) {
      // If there is sorting cached, load it into the View.
      if (action.sortable) {
        // If the action was cached, we should hit this block.
        this.sort.sort(action.sortable);
      } else {
        // Else apply the defaultSort.
        this.sort.sort(this.defaultSort);
      }
    }

    if (this.paginator) {
      // If we've stored a pageIndex and/or pageSize, retrieve accordingly.
      if (action.pageIndex) {
        this.paginator.pageIndex = action.pageIndex;
      } else { // Apply default pageIndex.
        this.paginator.pageIndex = 0;
      }

      if (action.pageSize) {
        this.paginator.pageSize = action.pageSize;
      } else { // Apply default pageSize.
        this.paginator.pageSize = 10;
      }
    }

    // Apply the sort & paginator to the View data.
    setTimeout(() => this.dataSource.sort = this.sort, 4000);
    setTimeout(() => this.dataSource.paginator = this.paginator, 4000);

    // Load the new action's data into the View:
    this.viewData = action.action;
    this.viewName = action.action.ActionName;
    this.refNumber = action.refNumber;

    // TODO: add uniquifiers/ids and use these as the sort for table

    const displayedColumns = this.viewData.Columns.map((c: { Name: any; }) => c.Name);
    displayedColumns[2] = 'Folder1';
    this.displayedColumns = ['select'].concat(displayedColumns);
    // tslint:disable-next-line: max-line-length
    const fetchedData = this.viewData.DataRows.map((r: { slice: (arg0: number, arg1: number) => { forEach: (arg0: (d: any, i: string | number) => any) => void; }; }) => {
      const row = {};
      r.slice(0, 9).forEach((d: any, i: string | number) => (row[this.displayedColumns[i]] = d));
      return row;
    });

    this.dataSource = new MatTableDataSource(fetchedData);
    this.loading = false;
  }

  // Stores the current Action, sort, and paginator in an ActionState object to be held in the action service's stateMap.
  cacheAction() {
    let actionState = new ActionState(this.viewData);

    // Determine the sort direction to store.
    let cachedStart: SortDirection;
    if (this.sort.direction == "desc") {
      cachedStart = 'desc';
    } else {
      cachedStart = 'asc';
    }

    // Create a Sortable so that we can re-apply this sort.
    actionState.sortable = {
      id: this.sort.active,
      start: cachedStart,
      disableClear: this.sort.disableClear
    };

    // Store the current pageIndex and pageSize.
    actionState.pageIndex = this.paginator.pageIndex;
    actionState.pageSize = this.paginator.pageSize;

    // Store the refNumber in the actionState for later retrieval.
    actionState.refNumber = this.refNumber;
    this.actionService.cacheAction(actionState);
  }

  ngOnInit() {
    // Subscribes to the action service's currentAction, populating this component with View data.
    this.actionService.currentAction.subscribe(action => this.loadAction(action));
  }

    /** Whether the number of selected elements matches the total number of rows. */
    isAllSelected() {
      const numSelected = this.selection.selected.length;
      const numRows = this.dataSource.data.length;
      return numSelected === numRows;
    }

    /** Selects all rows if they are not all selected; otherwise clear selection. */
    masterToggle() {
      this.isAllSelected()
        ? this.selection.clear()
        : this.dataSource.data.forEach((row: TableRow) => this.selection.select(row));
    }

    // Delete row functionality

    deleteRow() {
      console.log(this.selection);
      this.selection.selected.forEach(item => {
        const index: number = this.dataSource.data.findIndex((d: TableRow) => d === item);
        console.log(this.dataSource.data.findIndex((d: TableRow) => d === item));
        this.dataSource.data.splice(index, 1);
        this.dataSource = new MatTableDataSource<Element>(this.dataSource.data);
      });
      this.selection = new SelectionModel<TableRow>(true, []);
      this.actionService.deleteRow(this.selection).subscribe((response) => {
        console.log('Success!');
      });
    }


  ngOnDestroy() {

  }
}

view.service.ts

  deleteRow(selection: any): Observable<{}> {
console.log('testing service');
return this.http.delete<any>(`http://localhost:15217/actions/deleteRow`);

}

1 Ответ

1 голос
/ 07 февраля 2020

Есть 2 вещи, которые необходимо выполнить вашему коду в текущем виде:

  1. Передать идентификаторы выбранных строк на сервер каким-либо образом (обычно через URL в запросе DELETE). )
  2. Подпишитесь на наблюдаемое, чтобы материализовать его. В настоящее время http-запрос не будет выполняться, потому что его можно наблюдать без подписчиков. По крайней мере, вызов службы в компоненте должен выглядеть примерно так:
this.actionService.deleteRow(this.selection).subscribe((response) => {
  console.log('Success!');
});

Редактировать:

С номером 1 это зависит от того, какой метод вашего сервера похоже. Если он принимает массив цифр c идентификаторов, то view.service.ts будет выглядеть примерно так:

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

Я предполагаю здесь, как вы передаете информацию о таблице строки на ваш сервер. Если вы все еще боретесь с этим, вам нужно будет предоставить немного информации о конечной точке DELETE.

Edit 2:

Теперь мы немного больше знаем о том, как выглядят объекты ...

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