Angular Material:Mat Table 有时会实时更新有时不会

Avi*_*hek 5 typescript angular-material angular angular9 mat-dialog

我有一个调用GET请求的垫表。另外,我有一个 Mat Dialog,它接收数据并保存点击调用POST请求。一切正常,但有时在我单击“保存”按钮后表格会更新,但有时不会(我必须重新加载页面并查看它更新)。

mat-dialog.component.ts

onSubmit() {  // This method is called on the button click in Mat-Dialog
    if(this.formdata.invalid) {
      return;
    }
    this.adminService.createQuestionCategory(this.formdata.value).subscribe(reponse => {
      this._snackBar.open('New Question Category Added Successfully', '', {
        duration: 7500,
        horizontalPosition: this.horizontalPosition,
        verticalPosition: this.verticalPosition
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

main.component.ts

constructor(private adminCategory: AdminCategoryService, private fb: FormBuilder, public dialog: MatDialog) { 
    dialog.afterAllClosed.subscribe(() => {
      console.log(''); // This line gets called everytime on close of the modal
      this.getTableData(); // So this line also gets called but not re-render the template updated everytime
    });
}

openDialog() {
    this.dialog.open(CreateSectionModalComponent);
}

private getTableData() {
    this.columnsToDisplay = ['id', 'questionCategoryName', 'isActive', 'Action'];
    this.adminCategory.getQuestionCategory().subscribe((reponse: any) => {
          this.QuestionCategoryData = reponse.questionCategoryList;
          this.dataSource = new MatTableDataSource<QuestionCategory>(this.QuestionCategoryData);
          this.dataSource.paginator = this.paginator;
        }, error => {
          console.log(error);
        });
}

ngOnInit() {
    this.getTableData();
}
Run Code Online (Sandbox Code Playgroud)

有什么遗漏吗?

Nik*_*hil 0

将您的ngOnInit()和更改getTableData()为此

ngOnInit() {
   this.columnsToDisplay = ['id', 'questionCategoryName', 'isActive', 'Action'];
   this.dataSource = new MatTableDataSource<QuestionCategory>();
   this.dataSource.paginator = this.paginator;
   this.getTableData();
}   

private getTableData() {
    this.adminCategory.getQuestionCategory().subscribe((reponse: any) => {
          this.QuestionCategoryData = reponse.questionCategoryList;
          this.dataSource.data = this.QuestionCategoryData;
        }, error => {
          console.log(error);
        });
}
Run Code Online (Sandbox Code Playgroud)

在这里您正在初始化mat-table,然后只是更新数据。