Angular 如何正确设置角10中的MatSort

Angular 如何正确设置角10中的MatSort,angular,angular-material,Angular,Angular Material,我的mat表工作正常,但是只有在调用两次后,MatSort才能工作。下面是我从API获取数据并分配给dataSource变量的代码 .... @ViewChild(MatSort, { static: false }) sort: MatSort; dataSource = new MatTableDataSource(); .... ngOnInit(): void { this.getAllDepartments(); } getAllDepartments(): void {

我的mat表工作正常,但是只有在调用两次后,MatSort才能工作。下面是我从API获取数据并分配给
dataSource
变量的代码

....
@ViewChild(MatSort, { static: false }) sort: MatSort;

dataSource = new MatTableDataSource();
....

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

getAllDepartments(): void {
    this.departmentService.getDepartments().subscribe(
      (data: Department[]) => {
        this.departments = data;
        this.dataSource.data = this.departments;
        this.dataSource.sort = this.sort; // This supposed to be working but I need to call this method one more time for the sort to work properly
        this.isLoading = false;
      },
      (err: HttpErrorResponse) => {
        this.isLoading = false;
        this.openSnackBar(err.error.errors.msg);
      }
    );
  }

我也尝试过包括
ngAfterViewInit()
,但只有当我点击一个刷新按钮,通过调用
getAllDepartments()
方法刷新表数据时,它才会起作用。我不确定我错过了什么。

我也这样使用它,我没有问题-尝试移动this.dataSource.sort=this.sort;进入ngOnInit(在你调用这个.getAllDepartments()之前)-让我知道它是否有效。@angularQuestions不起作用:(嗯,好的,我将看到你的代码和我的代码之间的唯一区别是这一行-你能试着改变一下吗:@ViewChild(MatSort,{static:true})sort:MatSort;就像
@ViewChild(MatSort)sort:MatSort
之前,但后来我在一些帖子上读到,如果我的数据来自API,我应该包括
{static:false}
。无论哪种方式,它都不起作用,很抱歉,但只有这些信息我帮不上忙。但是如果你把代码放在Stackblitz演示中,我可以仔细看看。