When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc.
The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening?
To investigate the issue, I tested my web API and found that the last page number is indeed 2, so why is it being displayed as 3?
Below is the JSON data returned when running the API:
https://localhost:7235/api/items?pageNumber=0
{
"items": [
{
"id": 3,
"itemNameER": "قلم",
"itemNameEN": "pen",
"description": "1"
},
{
"id": 4,
"itemNameER": "قلم",
"itemNameEN": "pencil",
"description": null
},
{
"id": 5,
"itemNameER": "قلم",
"itemNameEN": "pen2",
"description": null
},
{
"id": 8,
"itemNameER": "car",
"itemNameEN": "car",
"description": "1"
},
{
"id": 9,
"itemNameER": "mobile",
"itemNameEN": "mobile",
"description": "1"
}
],
"pager": {
"numberOfPages": 2,
"currentPage": 1,
"totalRecords": 6
}
}
Based on the above data, the number of pages is 2, so why is it displaying 3?
Here is a snippet from the component.html file:
<table id="customers">
<tr>
<th>Id</th>
<th>ItemNameAR</th>
<th>ItemNameEN</th>
<th>Description</th>
</tr>
<tr
*ngFor="
let item of items
| paginate
: {
itemsPerPage: pager?.numberOfPages,
currentPage: pager?.currentPage,
totalItems: pager?.totalRecords
}
"
>
<td>{{item.id}}</td>
<td>{{item.itemNameAR}}</td>
<td>{{item.itemNameEN}}</td>
<td>{{item.description}}</td>
</tr>
</table>
<pagination-controls
previousLabel="Prev"
nextLabel="Next"
[responsive]="true"
(pageChange)="onPageChanged($event)"
></pagination-controls>
And here is part of the component.ts file:
export class ItemsComponent implements OnInit {
items?: ItemsData[] | undefined;
pager:any;
currentItem = null;
pageNumber:number=1;
constructor(private erpservice:ErpServiceService) { }
ngOnInit(): void {
this.retrieveAllItems();
}
onPageChanged(pageNumber: number) {
this.retrieveAllItems(pageNumber);
}
retrieveAllItems(pageNumber: number = 0): void {
this.erpservice.getAll(pageNumber)
.subscribe(
data => {
this.items=data.items;
this.pager=data.pager;
console.log(this.pager);
},
error => {
console.log(error);
});
}
}
This is how the services.ts looks like:
getAll(pageNumber: number): Observable<DataWrapper> {
let params = new HttpParams();
if (pageNumber)
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<DataWrapper>(baseUrl,httpOptions);
}
Lastly, the models used in this project are defined as follows:
export interface ItemsData {
id:number;
itemNameER:string;
itemNameAR:string;
itemNameEN:string;
description:string;
}
export interface DataWrapper {
items: ItemsData[];
pager:Pager;
}
export interface Pager {
numberOfPages:number;
currentPage:number;
totalRecords:number;
}
As for the final result obtained, you can view it here.