更改数据库后更新mat-table数据

时间:2018-01-23 22:13:07

标签: angular angular-material2

首先,我只想说我对Angular,Material和http相当新,所以如果你可以具体或者包含任何回复的代码片段,我会很感激。

我从db2数据库中提取数据并能够在mat-table中显示它。我可以使用matform和httpclientmodule编辑数据库;但是,当我进行更改时,我无法在不重新加载页面的情况下刷新表数据。

我尝试了paginator技巧(你将paginator值设置为当前值以触发表更新)但我不认为它在使用http时有效。

有没有人有这个好的解决方案?以下是我的一些代码:

import {Component, AfterViewInit, ViewChild, Injectable, OnInit, 
ChangeDetectorRef} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {MatPaginator, MatSort, MatTableDataSource, MatInputModule, 
MatFormField, MatInput, MatFormFieldModule} from '@angular/material';
import {Observable} from 'rxjs/Observable';
import {merge} from 'rxjs/observable/merge';
import {of as observableOf} from 'rxjs/observable/of';
import {catchError, map, tap} from 'rxjs/operators';
import {startWith} from 'rxjs/operators/startWith';
import {switchMap} from 'rxjs/operators/switchMap';
import {SelectionModel} from '@angular/cdk/collections';
import { FormGroup, FormControl } from '@angular/forms';

export class ContractorsDao {
  constructor(private http: HttpClient) {}

  // Sends request including which field to sort by and to sort asc or desc
  getContractorRecords(sort: string, order: string, page: number): 
Observable<Contractor[]> {
    const href = 'http://localhost:8080/pzapp-servlet';
    const requestUrl =
      `${href}/controllercontractors?message=getMstx&sort=${sort}&order=${order}`;
    return this.http.post<Contractor[]>(requestUrl, 'getMstx');
  }
}

@Component({
  selector: 'app-search-contractors',
  templateUrl: 'contractors.component.html',
  styleUrls: ['./contractors.component.css']
})
export class ContractorsComponent implements AfterViewInit, OnInit {

// Initialize items for contractor mat-table

  // Columns displayed on the table
  displayedColumns = [
    'contractor-name',
    'contractor-phone',
    'select-contractor'
  ];

  // Initialize mat-table data source
  dataSource = new MatTableDataSource<Contractor>();

  // Initialize local database
  contractorDatabase: ContractorsDao | null;

  // Initialize mat-table features
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  selection = new SelectionModel<Contractor>(false);

  editContractorForm: FormGroup;

  // Specific record selected
  activeRecord: Contractor;


  contractorsUrl = 'http://localhost:8080/pzapp-servlet/controllercontractors';

  // Triggered when record is selected from table
  viewRecord(row) {
    // Stores selected row for display
    this.activeRecord = row;
    this.editContractorForm = new FormGroup({
      NAME: new FormControl(this.activeRecord.NAME),
      PHON: new FormControl(this.activeRecord.PHON)
    });
  }

  // Takes filter text and filters table
  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); 
  // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  ngOnInit() {
    this.editContractorForm = new FormGroup({
    NAME: new FormControl(null),
    PHON: new FormControl(null),
    });
  }
  constructor(private http: HttpClient) {}

  ngAfterViewInit() {

    this.contractorDatabase = new ContractorsDao(this.http);
    this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);

    merge(this.sort.sortChange, this.paginator.page)
      .pipe(
      startWith({}),
      switchMap(() => {
        return this.contractorDatabase.getContractorRecords(
          this.sort.active, this.sort.direction, this.paginator.pageIndex);
      }),

    ).subscribe(data => this.dataSource.data = data);
    this.dataSource.paginator = this.paginator;

  }
  onSubmit(value: any) {
    this.http.put(this.contractorsUrl, this.editContractorForm.value).subscribe();

  //  this.dataSource.paginator = this.paginator;
  }
}

// Interface for PZCNTR listing
export interface Contractor {
  PCNAME: string;
  PCPHON: number;
}

2 个答案:

答案 0 :(得分:1)

只需创建ContractorsDao的新实例,并在成功修改后将其分配给contractorDatabase变量:

 onSubmit(value: any) {
    this.http.put(this.contractorsUrl, this.editContractorForm.value).subscribe(response => {
      this.contractorDatabase = new ContractorsDao(this.http);
      // here probably the rest of the code from ngAfterViewInit (so you can probably wrap it into a method)
    });    
  }

答案 1 :(得分:-1)

如果我理解了您的要求,您想要的是在数据库中更改数据后自动重新加载数据。我看到它的方式,你有以下选择。

  1. 使用计时器定期调用数据获取方法。这将是最容易实现的。见http://beyondscheme.com/2016/angular2-discussion-portal

    private refreshData(): void {
        //fetch data here
    }
    
    private subscribeToData(): void {
        this.timerSubscription = Observable.timer(5000).first().subscribe(() => this.refreshData());
    }
    
  2. 使用服务器端事件获取前端通知,然后获取数据更改。在这里查看示例。 https://stackoverflow.com/a/41540858/1849366

  3. 使用网络套接字。请参阅https://g00glen00b.be/spring-angular-sockjs/

  4. 您将在网络上获得更多上述方法的样本。