角材料表仅在单击表时显示项目

问题描述

当我单击表格时,项目仅显示在表格上。

首次加载页面时,表为空。我不知道为什么。

我从Rest-API Cloud Blobstorage检索数据,然后填充空数组。

代码如下:

import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

这里我导出接口PeriodicElement

//name of table column
export interface PeriodicElement {
  timestamp: string;  //need to be declared as string,angular table module requires it
  key: string;
  value: number;

}

导出类TableComponent实现OnInit {

displayedColumns: string[] = ['timestamp','key','value'];

ELEMENT_DATA: PeriodicElement[] = new Array<PeriodicElement>();

dataSource = new MatTableDataSource<PeriodicElement>(this.ELEMENT_DATA);
data_array: Array<JsonSchema> = [];

@ViewChild(MatSort,{ static: true }) sort: MatSort;  //sort data 
  @ViewChild(MatPaginator,{ static: true }) paginator: MatPaginator;  //for displaying data in the tables

constructor( privat DataStreamService: DataStreamService) {}

ngOnInit(): void {
this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

this.DataStreamService.getContents().then(results => {
this.data = results
......
....

....cut code .... 

this.ELEMENT_DATA.push(...tabledata)


}

在浏览器视图上,呈现表格时。 当我单击每页项目加载数据时,它会显示一个空表。

也许你们知道如何解决它。 我花了几天时间,没有发现问题。提前非常感谢

解决方法

尝试使用loadingData布尔值。以及为什么在Angular中使用Promises?尝试Observables。这不是React或纯JS,不是TypeScript的Angular,而是我们使用RxJ进行数据流传输。

export class YourComponent extends OnInit {

    loadingData = false;

     constructor(
         // try to make a difference here between
         // an instance started with "lowercase" and the service name
         private dataStreamService: DataStreamService
     ) {}
    
    ngOnInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    
        this.loadingData = true;
        this.dataStreamService.getContents().subscribe(results => {
           this.data = results;
           this.loadingData = false;
        });
    }
}

在您的html中,在表格容器标签上使用* ngIf指令:

<div *ngIf="!loadingData">
  <table>
   ... your content
  </table>
</div>

您的服务方法变为:

getContent(): Observable<any> {
   return this.http.get<any_type>(url).pipe()
     .tap(response => {
        // here you can modelate your data
        return response;
     });
}

由于getContent()是异步代码,因此您需要在加载数据后重新呈现html。使用loadingData属性,您可以告诉角度何时必须重新呈现页面。

,

尝试这样

ngOnInit(): void {
this.DataStreamService.getContents().then(results => {
  this.data = results; 
  this.dataSource = new MatTableDataSource(this.data);
  this.dataSource.paginator = this.paginator;
  this.dataSource.sort = this.sort;
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...