I am facing a pagination issue in Angular. Here is my HTML code:
<!-- A div element for pagination part at the bottom of the page -->
<div style="margin-left: 50%; margin-top: 20px; margin-bottom: 20px">
<ul class="pagination">
<li class="page-item"><button class="page-link" (click)="selectedPage('Previous')">Previous</button></li>
<li class="page-item" *ngFor="let p of page_num">
<button class="page-link" (click)="selectedPage(p)" routerLink="/games/page/{{p}}">{{p}}</button>
</li>
<li class="page-item"><button class="page-link" (click)="selectedPage('Next')">Next</button></li>
</ul>
</div>
Explanation is that this code sends the clicked page number to my TypeScript file containing this piece of code:
/*Created an element called currentPage to get the current page and send it to getGames func (my subscribe func), this element will be dynamically change, but will start from 1*/
currentPage = 1;
//Created a page_num cevtor that will be change when page selected
page_num : number[] = [this.currentPage, this.currentPage+1, this.currentPage+2];
//Created a func called selectedPage in order to adjust the page numbers and send corretc page num to funcs, all the data I am using is sotred in a vector called gamesVector
public selectedPage(page) {
//If clicked option was 'Previous'
if(page == 'Previous') {
//If previous of that page is not null
if(this.gamesVector.previous !== null) {
this.currentPage--;
this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
this.router.navigate(['/games/page/' + this.currentPage])
}
else
alert('You are already in the first page')
}
//If clicked option was 'Next'
else if(page == 'Next') {
//If next of that page is not null
if(this.gamesVector.next !== null) {
this.currentPage++;
this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
this.router.navigate(['/games/page/' + this.currentPage])
}
else
alert('You are already in the last page')
}
//If the clicked option was a page number
else {
this.currentPage = page;
this.page_num = [this.currentPage, this.currentPage+1, this.currentPage+2];
}
//Then call the games subscribe function with the new page number, so the games can be refreshed
this.gameAndCatServ.getGames(this.currentPage).subscribe(data => {
this.gamesVector = data;
})
//To scroll all the way up when changing the page
window.scrollTo(0, 0)
}
The functionality works well, but there are issues when the page number is changed directly from the URL or by using the browser's back button. How can I ensure that the page refreshes in such scenarios?