【问题标题】:Angular Material Datatable not sorting data from Http requestAngular Material Datatable 未对来自 Http 请求的数据进行排序
【发布时间】:2018-12-09 19:55:22
【问题描述】:

我正在使用带有 Http 请求的 Angular Material 数据表来获取数据。

但是,它不是对数据表中的数据进行排序。

export class ContactComponent implements OnInit, AfterViewInit {
  displayedColumns: string[] = [
    "firstname",
    "middlename",
    "lastname",
    "status",
    "dateofbirth"
  ];     
  selected;
  dataSource = new MatTableDataSource<Yuvak>();

  constructor(
    private router: Router,
    private dialogService: NbDialogService,
    private contactService: ContactService
  ) { }

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

  ngOnInit() {
    this.contactService.getAllUser().subscribe(
      data => {
        this.dataSource.data = data.data.user;
      },
      error => {
        console.log("There was an error while retrieving Users !!!" + error);
      }
    )
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
      }

上面是我的 ts 文件。以前,当我从本地 json 文件加载数据时,它在构造函数中运行良好。但是,现在我从 GET 请求中获取数据。

【问题讨论】:

    标签: angular angular-material2 angular-material-6


    【解决方案1】:

    检查您显示的列名称与您用作列标题的列名称。其他一切看起来都还可以。如果可能,请发布您的模板文件。

    检查你的 html 文件后试试这个。

    ngOnInit() {
        this.contactService.getAllUser().subscribe(
          data => {
            this.dataSource.data = data.data.user;
    this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
          },
          error => {
            console.log("There was an error while retrieving Users !!!" + error);
          }
        )
      }
    

    【讨论】:

      【解决方案2】:

      尝试将dataSource = new MatTableDataSource&lt;Yuvak&gt;(); 替换为dataSource: Yuvak[] = [],将this.dataSource.data = data.data.user; 替换为this.dataSource = data

      【讨论】:

      • 我正在使用这个“data.data.user”,因为我正在访问我的内部嵌套对象。
      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多