I am using a back-end server (Java Spring) that has Pager enabled. I am loading 100 records per page on a HTTP call.
On angular2 service, it is consuming the API ca
I solved this problem with LocalDataSource
.
HTML:
<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
TS:
source: LocalDataSource = new LocalDataSource();
pageSize = 25;
ngOnInit() {
this.source.onChanged().subscribe((change) => {
if (change.action === 'page') {
this.pageChange(change.paging.page);
}
});
}
pageChange(pageIndex) {
const loadedRecordCount = this.source.count();
const lastRequestedRecordIndex = pageIndex * this.pageSize;
if (loadedRecordCount <= lastRequestedRecordIndex) {
let myFilter; //This is your filter.
myFilter.startIndex = loadedRecordCount + 1;
myFilter.recordCount = this.pageSize + 100; //extra 100 records improves UX.
this.myService.getData(myFilter) //.toPromise()
.then(data => {
if (this.source.count() > 0){
data.forEach(d => this.source.add(d));
this.source.getAll()
.then(d => this.source.load(d))
}
else
this.source.load(data);
})
}
}
Also if you need to customize request to back-end there is configuration parameters for ServerDataSource
that is used for data retrieving/pagination/sorting.
When you have your endpoint for some entity on {endPointBase}/ng2-smart-table, where you are processing key_like request params (i.e: @Requestparam Map to spring data Example) , you can use on client side:
export class SpringDataSource extends ServerDataSource {
constructor(http: HttpClient, endPointBase: string) {
const serverSourceConf = new ServerSourceConf();
serverSourceConf.dataKey = 'content';
serverSourceConf.endPoint = endPointBase + `/ng2-smart-table`;
serverSourceConf.pagerLimitKey = 'size';
serverSourceConf.pagerPageKey = 'page';
serverSourceConf.sortFieldKey = 'sort';
serverSourceConf.totalKey = 'totalElements';
super(http, serverSourceConf);
}
protected addPagerRequestParams(httpParams: HttpParams): HttpParams {
const paging = this.getPaging();
return httpParams
.set(this.conf.pagerPageKey, (paging.page - 1).toString())
.set(this.conf.pagerLimitKey, paging.perPage.toString());
}
protected addSortRequestParams(httpParams: HttpParams): HttpParams {
const sort: {field: string, direction: string}[] = this.getSort();
sort.forEach((column) => {
httpParams = httpParams.append(this.conf.sortFieldKey, `${column.field},${column.direction}`);
});
return httpParams;
}
}
Try to set the settings to the smart-table like this
<ng2-smart-table #grid [settings]="settings" ... >
And at your component, define the settings, something like this:
public settings: TableSettings = new TableSettings();
ngOnInit(): void {
...
this.settings.pager.display = true;
this.settings.pager.perPage = 100;
...
}