here i have a issue while working with angular paginator . here i am getting data like below
Response One:
{
"Tabledata"
First of all, It is recommended to avoid using a token for pagination.
You can simply use skip
and limit
. Something that you are currently using is pageSize
which works as limit and
let us call a new param currentPage
as skip.
Anyways moving ahead with token, the implementation logic is as below.
Step 1
You will need following member variables for component in which paginator is present.
defaultPayload = {
searchParams : "",
pageSize : 2,
currentPage : 1,
token : ""
};
totalLength = 0;
the defaultPayload
is argument to your service through which new data comes in.
You need currentPage
at angular service level for tokenMap
implementation will explain
in sometime.
totalLength
as you have already binded it to mat-paginator.
Before moving ahead, you have a question about totalLength
. As shown in image your totalLength
is 2, As the pageSize
is 10, the functionality of next and previous are disabled. It makes sense too. If your response RecordsCount
is 50, it will show up if you have set the member variable as the following step demonstrates.
Step 2 On load
Let's say we are subscribed to the api service as below in ngInit
ngOnInit() {
this.getDataService(this.defaultPayload)
.subscribe(
res => {
this.defaultPayload.token = paging['token'];
this.totalLength = paging['RecordsCount'];
},
err => {}
);
}
On response, we are :
RecordsCount
in totalLength (which you might be expecting 50, but its 2)Step 3 On event
PageEvents(event){
console.log("event", event, this.defaultPayload);
const pageSize = event.pageSize;
const currentPage = event.pageIndex + 1;
this.defaultPayload.pageSize = pageSize;
this.defaultPayload.currentPage = currentPage;
this.getDataService(this.defaultPayload)
}
Note We are just resetting our request payload again as per new event and make a service call.
Step 4 Service
let say we have some service as follows that is responsible for providing data. We need to maintain some kind of storage for token. you might use localstorage or simply an object as below whatever suits your need. This is needed because we need to maintain tokens for all (old) prev and (new) next page events.
constructor() {
this.tokenMap = {};
}
getDataService({...options, currentPage}){
options.token = findToken(currentPage)
//http request using {options}
//on response setToken
this.setTokenMap(options.currentPage, response['token])
return responseData
}
findToken(page){
return this.tokenMap[page || 1] || "";
}
setTokenMap(page, token){
this.tokenMap[page] = token;
}
This service will find the token while making an api call, and also set the new token as per currentPage, hence you don't have to bother about token in component. This will separate your concerns of the token logic and component paginator data.