问题描述
我正在尝试实现一个带有分页的 Angular 材料表,该表连接到后端,从 Azure 表存储中检索数据。
我知道,Table Storage 支持 ExecuteQuerySegmentedAsync,它返回 TableContinuationToken。看起来不错。所以在前端,我得到了这样的信息:
interface IPagedResult<T> {
items: T[];
isFinalPage: boolean;
continuationToken: string;
}
interface ILog {
enqueuedDate: string;
...
}
component.ts 中的某处:
private logsTableSource: MatTableDataSource<ILog>;
@ViewChild(MatPaginator)paginator: MatPaginator;
ngAfterViewInit() {
myService.GetRecords(this.paginator.pageSize)
.subscribe(
(res: IPagedResult<ILog>) => {
this.logsTableSource = new MatTableDataSource<ILog>(res.items);
});
}
现在我想知道,如何获得页数?并让服务器知道我想要什么特定页面?
事实上,我可以用这个 continuationToken 做什么?
解决方法
您链接到的 TableContinuationToken
文档还指出:
可能通过 TableResultSegment 对象返回部分结果集的方法还会返回一个继续标记,该标记可用于后续调用以返回下一组可用结果。
这意味着令牌可用于获取下一组可用结果,您不能将它们用作分页索引。无法为结果的第 7 页制作 TableContinuationToken。
,正如@rickvdbosch 所说,TableContinuationToken
预计只会向前发展。在分页器中进行了一些更改后,我只能向前和向后移动。看起来不错,对我有用:
如果有人感兴趣。以下是变化:
- 实现您自己的
MatPaginatorIntl
以删除页面标签。我的样子是这样的:
@Injectable()
export class LogsPaginator extends MatPaginatorIntl {
public getRangeLabel = function (page: number,pageSize: number,length: number) {
return '';
};
}
- 缓存您之前加载的项目,因为我们可以仅使用 TableContinuationToken 向前移动。您的 component.ts 应如下所示:
export class LogsComponent {
// As table storage does not support paging per index,we should cache already loaded logs and use continuation token if needed.
private cachedLogs: ILog[] = [];
private cachedIndexes: number[] = [];
private continuationToken = '';
ngOnInit() {
this.paginator.page.subscribe(this.pageChanged.bind(this));
}
async ngAfterViewInit() {
await this.loadLogs();
}
private async pageChanged(event: PageEvent) {
if (event.previousPageIndex < event.pageIndex && this.cachedIndexes.indexOf(event.pageIndex) === -1) {
await this.loadLogs();
} else {
this.redrawTable();
}
}
private redrawTable() {
const start = this.paginator.pageIndex * this.paginator.pageSize;
const end = start + this.paginator.pageSize;
this.logsTableSource.data = this.cachedLogs.slice(start,end);
}
private async loadLogs() {
const res = await this.myService.GetLogs(this.paginator.pageSize,this.continuationToken).toPromise();
this.cachedIndexes.push(this.paginator.pageIndex);
this.cachedLogs.push(...res.items);
this.paginator.length = res.isFinalPage ? this.cachedLogs.length : this.cachedLogs.length + 1;
this.continuationToken = res.continuationToken;
this.redrawTable();
}
}