Я пытаюсь сделать стол, используя угловой материал .Проблема, с которой я сталкиваюсь, заключается в том, что в стартовой таблице не отображаются никакие данные.Но нумерация страниц обновила количество данных.Невозможно понять, как сделать данные доступными, как только компонент загрузится.
Как вы можете видеть справа, он показывает 52 всего имеющихся записей.
И как только я щелкаю заголовок таблицы для сортировки или нажимаю следующую кнопку нумерации страниц, строки заполняются данными.
Было бы очень полезнопредложения по ее исправлению.
Спасибо
HTML-файл
<div class="mat-elevation-z8">
<table mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
<!-- Id Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
<td mat-cell *matCellDef="let row">{{row.snipsOutput.id}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="input">
<th mat-header-cell *matHeaderCellDef mat-header>User Query</th>
<td mat-cell *matCellDef="let row">{{row.snipsOutput.input}}</td>
</ng-container>
<!-- Hotword Column -->
<ng-container matColumnDef="hotword">
<th mat-header-cell *matHeaderCellDef mat-header>Hotword</th>
<td mat-cell *matCellDef="let row">{{row.snipsOutput.hotword}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator
[length]="dataSource.data.length"
[pageIndex]="0"
[pageSize]="10"
[pageSizeOptions]="[10, 50, 100, 250]">
</mat-paginator>
</div>
NluDataTableComponent.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { NluDataTableDataSource } from './nlu-data-table-datasource';
import { PfivaDataService } from '../services/pfiva-data.service';
@Component({
selector: 'app-nlu-data-table',
templateUrl: './nlu-data-table.component.html',
styleUrls: ['./nlu-data-table.component.css']
})
export class NluDataTableComponent implements OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
dataSource: NluDataTableDataSource;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'input', 'hotword', 'intent', 'timestamp', 'feedbackQuery', 'feedbackUserResponse', 'feedbackTimestamp'];
constructor(private pfivaDataService: PfivaDataService) {
}
ngOnInit() {
this.dataSource = new NluDataTableDataSource(this.paginator, this.sort, this.pfivaDataService);
}
}
NluDataTableDataSource.ts
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { NLUData } from '../data-model/NLUData';
import { PfivaDataService } from '../services/pfiva-data.service';
/**
* Data source for the NluDataTable view. This class should
* encapsulate all logic for fetching and manipulating the displayed data
* (including sorting, pagination, and filtering).
*/
export class NluDataTableDataSource extends DataSource<NLUData> {
//data: NluDataTableItem[] = EXAMPLE_DATA;
data: NLUData[] = [];
constructor(private paginator: MatPaginator,
private sort: MatSort, private pfivaDataService: PfivaDataService) {
super();
this.fetchNLUData();
}
/**
* Connect this data source to the table. The table will only update when
* the returned stream emits new items.
* @returns A stream of the items to be rendered.
*/
connect(): Observable<NLUData[]> {
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
// Set the paginators length
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
/**
* Called when the table is being destroyed. Use this function, to clean up
* any open connections or free any held resources that were set up during connect.
*/
disconnect() {}
private fetchNLUData() {
this.pfivaDataService.getNLUData()
.subscribe(
(nluData: NLUData[]) => this.data = nluData,
(error) => console.log(error)
);
}
/**
* Paginate the data (client-side). If you're using server-side pagination,
* this would be replaced by requesting the appropriate data from the server.
*/
private getPagedData(data: NLUData[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
/**
* Sort the data (client-side). If you're using server-side sorting,
* this would be replaced by requesting the appropriate data from the server.
*/
private getSortedData(data: NLUData[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'id': return compare(+a.snipsOutput.id, +b.snipsOutput.id, isAsc);
default: return 0;
}
});
}
}
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}