这是我解决所有这些问题的方法。
1:确保后端(API)启用了 cors 以向客户端显示“X-Pagination”标头,如下所示:
app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders(new string[] { "X-Pagination"}));
2:HTML:
<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
3:服务:
getClients(pageNumber: number, pageSize: number): Observable<any> {
const headers = new HttpHeaders({'Content-Type': 'application/json','Accept': 'application/json' });
let params = new HttpParams();
params = params.append('PageNumber',pageNumber.toString());
params = params.append('PageSize',pageSize.toString());
return this.http.get<ClientDto[]>(API_URL, {headers: headers, observe: "response" as "body", responseType: "json", params} );
}
4:TS:
export class ListClientComponent implements OnInit {
source: LocalDataSource;
pageSize = 30;
currentPage = 1;
showPerPage = 10;
totalCount;
constructor(private service: ClientService,private router: Router) {
this.initData();
}
public settings = {
mode: 'external',
pager:{
display: true,
perPage: this.showPerPage,
},
actions: {
add:false,
edit:true,
delete:false
},
columns: {
clientId: {
title: 'CI',
},
name: {
title: 'Name'
},
instagramName: {
title: 'Instagram'
},
type: {
title: 'Type'
},
phone: {
title: 'Phone'
},
gender: {
title: 'Gender'
},
age: {
title: 'Age'
},
city: {
title: 'City'
},
email: {
title: 'Email'
}
},
};
ngOnInit() {
this.initOnChagedData();
}
onEdit(event){
console.log(event.data.clientId);
this.router.navigate(['/clients/update-client/'+ event.data.clientId]) ;
}
initData(){
this.source = new LocalDataSource();
this.service.getClients(this.currentPage, this.pageSize).subscribe( (result: HttpResponse<any>) => {
if(!result){
return;
}
this.source.load(result.body);
this.totalCount = JSON.parse(result.headers.get("X-Pagination"));
this.totalCount = this.totalCount["totalCount"];
console.log(this.source.count());
}
)
}
initOnChagedData(){
this.source.onChanged().subscribe((change) => {
if (change.action === 'page') {
this.pageChange(change.paging.page);
}
});
}
pageChange(pageIndex) {
var getNew = pageIndex * this.showPerPage;
if( getNew >= this.source.count() && getNew < this.totalCount){
this.currentPage = this.currentPage + 1;
this.service.getClients(this.currentPage, this.pageSize).subscribe( result => {
if(!result){
return;
}
result.body.forEach(element => {
this.source.add(element);
});
})
}
}
}
您应该注意到 pageSize = 我们从后端提取的总数据并显示每页 = 我们在表中显示的总数据。
该算法被设计为仅在必要时从 API 中提取,即当客户端到达数据在内存中结束的页面时,它会要求再多 30 条数据有另外 3 个页面,并且也不会忘记另外 3 个页面之前已经提取的。