Angular Material : Mat Table sometimes get updated in real-time sometimes not

标签 angular typescript angular-material 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
      });
    });
  }

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();
}

有什么遗漏吗?

最佳答案

更改您的 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);
        });
}

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

关于 Angular Material : Mat Table sometimes get updated in real-time sometimes not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62321504/

相关文章:

javascript - 为什么在 Angular 项目中没有 Angular-CLI 为 'model' 生成命令?

angular - ngrx:集合中每个元素的加载状态

json - 如何将 Laravel 5.4 与 Angular 4 集成

javascript - 在窗口函数 typescript 上访问类数据

angular - 如何在 Angular Material 的多选下拉菜单中实现搜索功能

angular - MatTableDataSource : cannot read property 'length' of undefined

angular - 在 Angular TestBed 中模拟 Firestore 集合

node.js - ts-node 找不到我的类型定义文件

javascript - Angular 2 测试应用程序卡在加载中

angular - 在 FormArray 中访问 FormGroup 中的 FormControl