简体   繁体   中英

Angular 7 / Material DataTable not updating after any operation

I'm building an Angular 7 application using @angular/material . When I load the application for the first time, the Datatable renders correctly, but when I call any function, example - delUser , after deleting a user from the database, it's meant to render the table immediately, but it doesn't until I refresh the whole page. I've tried everything, but to no avail.

Here's my code:

import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';

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

  pgtitle:string = "Manage Users";

  dataSource:any;
  displayedColumns:string[] = ['userName','email','roleId','userType','Actions'];

    @ViewChild(MatSort, {static: true}) sort: MatSort;
    @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(
    private service:UserService
  ){}      

  ngOnInit(): void {
    this.getAllUsers();
  }    

  applyFilter(filterValue:String){
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  getAllUsers(){   
    this.service.getAllUsers().subscribe( result => {
        this.dataSource = new MatTableDataSource(result); 
        this.dataSource.paginator = this.paginator; 
        this.dataSource.sort = this.sort;
    });
  } 

  delUser(id){
    this.service.deleteUser(id).subscribe(result => {
    this.getAllUsers();   
  });

}

Maybe you can try this:

this.service.getAllUsers().subscribe( result => {
    this.dataSource = null; //add this
    this.dataSource = new MatTableDataSource(result); 
    this.dataSource.paginator = this.paginator; 
    this.dataSource.sort = this.sort;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM