【问题标题】:table not refreshing after creating or updating the data创建或更新数据后表不刷新
【发布时间】:2020-07-24 14:45:54
【问题描述】:

我正在集成 Api,我面临一个问题,在创建或更新数据时表不会刷新,除非在硬刷新或浏览器刷新之前,我也尝试了更改检测器,但没有解决方案。我尝试了changedetector ref , new MatTableDataSource 但表格未刷新。抱歉发布长代码。




create row.ts
--------------------------------------
import { Component, OnInit, Inject, Input, Output,ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { FormGroup, FormControl, Validators, FormGroupDirective, NgForm, FormBuilder, FormArray } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { HelperService } from 'app/services/helper.service';
import { StorageService } from 'app/admin/services/storage.service';
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
import { ValidatorService } from 'app/services/validator.service';
import { RoomService } from 'app/admin/services/room.service';

export class MyErrorStateMatcher implements ErrorStateMatcher {

    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
      const isSubmitted = form && form.submitted;
      return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
  
  }
  
  @Component({
    selector: 'app-create-rows',
    templateUrl: './create-rows.component.html',
    styleUrls: ['./create-rows.component.scss']
  })
  export class CreateRowsComponent implements OnInit {

    public statusTypes: any[] = ['N/A', 'Quarantine', 'Release', 'Reject'];
    public rows: FormArray;
    public rowsArray: any[] = [];
    public matcher = new MyErrorStateMatcher();
    public editMode: boolean = false;
    public availablerows: any;
    public availableSeqId:number[] =[];
    public addedItem:boolean = false;
    public clicked=false;
    public fetchedRooms:any;
    
    constructor(private dialogRef: MatDialogRef<CreateRowsComponent>, @Inject(MAT_DIALOG_DATA) public dialogData: any,
    private helper: HelperService, private formBuilder: FormBuilder,
    private storageSrv: StorageService,private validatorService:ValidatorService, private roomSrv:RoomService,private cd: ChangeDetectorRef,
    private spinnerService: Ng4LoadingSpinnerService) {
    this.rows = this.rowDiagForm.get('rows') as FormArray;
  }
  ngOnInit() {
    this.storageSrv.sharedRoomRow.distinctUntilChanged().subscribe(data => {
      if (data) {
        this.rowDiagForm.patchValue(data);
        this.rows.at(0).get('statusType').clearValidators();
        this.rows.at(0).get('statusType').updateValueAndValidity();
        this.editMode = true;
      }
    });
    this.roomSrv.getAllRooms(this.helper.getLocation(),{}).subscribe(res=> this.fetchedRooms = res.body);
    this.rowsArray = this.rowDiagForm.get('rows').value;
   
  }
 
  // Row Form
  public rowDiagForm = this.formBuilder.group({
    id: this.formBuilder.control(''),
    name: this.formBuilder.control(''),
    statusType: this.formBuilder.control(''),
    roomId:this.formBuilder.control(''),
    seqId: this.formBuilder.control(''),
    rows: this.formBuilder.array([this.createItem()], Validators.required),
  });
   /** form array **/
   createItem(): FormGroup {
    return this.formBuilder.group({
      name: this.formBuilder.control(''),
      seqId: this.formBuilder.control(''),
      isReUsed: this.formBuilder.control(false),
      statusType: this.formBuilder.control('', [Validators.required])
    });
  }
  /** ADD Field **/
  addItem(): void {
    this.addedItem = true;
    this.rows = this.rowDiagForm.get('rows') as FormArray;
    this.rows.push(this.createItem());
    this.rowsArray = this.rows.value;
  }


  /** REMOVE chips **/
  removeItem(index): void {
    if (index != 0) {
      this.rows = this.rowDiagForm.get('rows') as FormArray;
      this.rows.removeAt(index);
      this.rowsArray.splice(index, 1);
    }
  }
  getAvailableSeqIds(){
    let rowObj = this.rowDiagForm.value;
     this.storageSrv.getSeqIdsForRoomRow(rowObj.roomId).subscribe(res => { this.availableSeqId = res.body });
  }
   // Re Use
   reUse(mainIndex) {
    var arrayControl = this.rowDiagForm.get('rows') as FormArray;
    this.rowsArray[mainIndex].isReUsed = !this.rowsArray[mainIndex].isReUsed;
    this.rowDiagForm.get('rows').patchValue(this.rowsArray);
    arrayControl.at(mainIndex).get('seqId').clearValidators();
    arrayControl.at(mainIndex).get('seqId').updateValueAndValidity();
    arrayControl.at(mainIndex).get('seqId').patchValue('');
  }
   /** DESTROY editmode **/
   ngOnDestroy() {
    this.editMode = false;
    this.cd.detach();
  }
   /** CREATE a Rows **/
   create() {
     this.validatorService.userValidator(this.editMode?'update':'create').then(res => {
        if(res.val) {
          let rowObj = this.rowDiagForm.value;
          this.clicked=false;
          delete res.val;
          rowObj['locationId']=this.helper.getLocation();
         if (this.rowDiagForm.valid) {
             if (this.editMode) {
                      this.storageSrv.updateRowForRoom(rowObj,res).subscribe(data => {
                      this.cd.markForCheck();
                      this.helper.showSnackbar('Successfully Updated Row !');
                      this.dialogRef.close(this.rowDiagForm.value);
                      this.storageSrv.setSharedRoomRow(data);
                      this.spinnerService.hide();
                  })
                }
             else {
                  delete rowObj["id"];
                  let generatedRow = this.generateRows(rowObj);
                  this.storageSrv.addRowForRoom(rowObj.roomId,generatedRow ,res).subscribe(data => {
                      this.cd.markForCheck();
                      this.helper.showSnackbar('Successfully Created Row!');
                      this.dialogRef.close(this.rowDiagForm.value);
                      this.storageSrv.setSharedRoomRow(data);
                      this.spinnerService.hide();
                      }, err => {
                      console.log(err);
                     })
               }
            }
          }

     })
    }
   
    // Generate  rows
  generateRows(rowObj) {
    for (let i = 0; i < rowObj.rows.length; i++) {
     { rowObj.rows[i].name = 'Row'; rowObj.rows[i].roomId =rowObj.roomId; }
    }
    return rowObj.rows;
  }
   /** CLOSE mat dialog **/
   close() {
    this.dialogRef.close(null);
  }

  }
row.ts
-------------------------------
import { Component, OnInit ,ViewChild,ChangeDetectorRef } from '@angular/core';
import { MatPaginator, MatSort, MatDialog, MatTableDataSource, MatDialogConfig, PageEvent,Sort } from '@angular/material';
import { StorageService } from '../../../services/storage.service';
import { CreateRowsComponent } from './create-rows/create-rows.component';
import { ValidatorService } from 'app/services/validator.service';
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
import { HelperService } from 'app/services/helper.service';
import { StorageModel } from 'app/models/storage.model';
import { CommonApiService } from 'app/services/common-api.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-rows',
  templateUrl: './rows.component.html',
  styleUrls: ['./rows.component.scss']
})
export class RowsComponent implements OnInit {
  public displayedColumns: string[] = ['name', 'roomName',   'statustype', 'action'];
  public dataSource = new MatTableDataSource();
  public editMode: boolean = false;
  public viewMode: boolean = true;
  public data: any;
  public paginate: any = {};
  public totalRows: number;
  public pageEvent: PageEvent;
  public roomRows:any;

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

  constructor(private dialog: MatDialog, private storageSrv: StorageService, private validatorService: ValidatorService, private spinnerService: Ng4LoadingSpinnerService,
    private helperService: HelperService, private commonSrv: CommonApiService, private actRoute: ActivatedRoute, private router: Router,private cd:ChangeDetectorRef) { }

  ngOnInit() {
    this.setDefaultParams();
    this.refreshForRows();
  }
   /** DELETE a freezer **/
   onDeleteRoomRows(row, index) {
    this.validatorService.userValidator('delete').then(res => {
      if (res.val) {
        delete res.val;
        this.storageSrv.deleteRoomRows(row,res).subscribe(data => {
          let rowData = this.dataSource.data;
          rowData.splice(Number(index), 1);
          this.dataSource.data = rowData;
          this.paginateRoomRows(false);
        },err=>{
            this.helperService.showSnackbar(err.error.message,true)});
      }
    }).catch(err => {
      console.error("Delete Freezer Failed", err);
    });
  }
 /** EDIT a freezer **/
 onEditRoomRows(rowObj) {
  this.editMode = true;
  this.openCreateRow(rowObj);
}
  /** open CREAT Row **/
  openCreateRow(newData?): void {
    if (newData) {
      this.storageSrv.setSharedRoomRow(newData);
    } else {
      this.storageSrv.setSharedRoomRow("");
      this.storageSrv.sendCurrentRoomRow("");
      this.storageSrv.sendUpdatedRoomRow("");
    }
  
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    let dialogRef = this.dialog.open(CreateRowsComponent, {
      width: '700px',
    
    });
  }
   // Set Default Params
   setDefaultParams() {
    this.paginate = this.actRoute.snapshot.data['params'];
    let reqParams = this.commonSrv.createParam(this.paginate);
    this.router.navigate([], { queryParams: reqParams })
    this.dataSource = new MatTableDataSource( this.actRoute.snapshot.data['roomRows'].body);
    this.dataSource.data.forEach(data=>{
          this.roomRows=data;
    });
    this.totalRows = this.actRoute.snapshot.data['roomRows'].headers.get('X-Total-Count');
  }
//refresh Rows
refreshForRows(){
  this.storageSrv.sharedRoomRow.distinctUntilChanged().subscribe(data => {
    if (data) {
        this.setDefaultParams();
        this.editMode = true;
    }else{
        this.setDefaultParams();
    }
  });
} 
service.ts
-------------------
//Rows
   private createdRoomRows = new BehaviorSubject("");
   public currentRoomRow = this.createdRoomRows.asObservable();
   private sharableRoomRow = new BehaviorSubject<any>("");
   public sharedRoomRow = this.sharableRoomRow.asObservable();
   private updatedRoomRow= new BehaviorSubject<any>("");
   public updatedCurrentRoomRow=this.updatedRoomRow.asObservable();
 //roomRow
  sendCurrentRoomRow(rowObj){
    this.createdRoomRows.next(rowObj);
  }
  setSharedRoomRow(rowObj){
    this.sharableRoomRow.next(rowObj);
    console.log(rowObj);
  }
  sendUpdatedRoomRow(rowObj){
    this.updatedRoomRow.next(rowObj);
  }
`````

【问题讨论】:

  • 我认为您可能需要使用 ViewChild 和 renderRows() 刷新表格,因为这个 SO(在更新的答案中)显示:stackoverflow.com/questions/59170701/…
  • 更新和创建调用表数据API后

标签: angular


【解决方案1】:

我在服务中使用了行为主体和 observable,并在创建或更新数据时在 ngoni 中调用它。现在它工作正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2015-06-30
    相关资源
    最近更新 更多