Page number automatically resets 1 after switching pages with angular

823 Views Asked by At

I don't know why pageNumber in bookParams auto reset to 1 after I changed the page from 1 to 2.

export class BookListComponent implements OnInit {
  books: Book[];
  bookParams: BookParams;
  pagination: Pagination;
  constructor(private bookService: BookService, private accountService: AccountService) {
    accountService.currentUser$.pipe(take(1)).subscribe(user => {
      this.bookParams = new BookParams(user);
      console.log("contructor " + this.bookParams.pageNumber);
    })
  }

  ngOnInit(): void {
    let a = this.bookParams;
    this.loadBooks();
  }

  loadBooks() {
    console.log("loadBooks" + this.bookParams.pageNumber);
    this.bookService.getBooks(this.bookParams).subscribe(response => {
        this.books = response.result;
        this.pagination = response.pagination;
        this.pagination.currentPage = 1;
    })
  }
  pageChanged(event: any) {
    console.log("PageChange "+event.page);
    this.bookParams.pageNumber = event.page;
    this.loadBooks();
  }
}

BookParams.ts

export class BookParams {
    pageSize = 8;
    pageNumber = 1;
}

enter image description here

pic after I click change page

enter image description here

1

There are 1 best solutions below

1
On

Your pageChanged function calls your loadBooks function, which in turn has this line:

this.pagination.currentPage = 1;

Hence, it will be pointing to first page after every page change (that is assuming changing pages calls the pageChanged function - we don't have enough information with what you posted.