Lately, the project I've been focused on involves managing numerous lists with search, sort, and pagination functionalities. I have successfully implemented data fetching from an API based on these criteria.
Recently, a new requirement emerged - the ability for users to share specific lists by generating shareable links. For example, if User A customizes their list by sorting it by 'Customer' and navigating to page 5, they should be able to send that link to User B who will then open the same list on page 5 sorted by 'Customer'. Simple concept, but crucial feature.
I devised a solution where I subscribe to queryParams on ActiveRoute, parse these parameters, and reload the list accordingly. Here's a snippet of the code:
Component Template HTML:
<ngb-pagination [collectionSize]="size" [page]="page" (pageChange)="changePage" >
</ngb-pagination>
<pre>Current page: {{page}}</pre>
Component Typescript:
ngOnInit() {
this.route
.queryParams
.subscribe(queryParams => {
this.sort = queryParams['sort'];
this.search = queryParams['search'];
this.page= +queryParams['page'] || 1;
this.refresh();
});
this.refresh();
}
refresh() : void {
this.transactionsService.fetch({
from: (this.page - 1) * this.size,
take: this.size,
search: this.search,
sort: this.sort
}).subscribe(data => {
this.entities = data.entities;
this.total_size = data.total;
});
}
changePage(event: number) : void {
this.router.navigate(['/transactions'], {
queryParams : { page: event},
queryParamsHandling: 'merge'
});
}
However, I am not completely satisfied with this approach as I feel it is somewhat messy, especially since all actions are routed through the primary router. I am exploring ways to optimize this process such as avoiding subscription in ngOnInit and enhancing the changePage function logic:
changePage(event: number) : void {
this.page = event;
this.refresh();
// Need to find a way to update query params without triggering navigation
this.route.queryParams['page'] = this.page; ??????
}'
Seeking guidance on how to achieve this effectively.