I am creating a component using Angular 18 that shows a list of clients and one of the characteristics of this component is that it must save in the localstorage the status of the applied filters and the number of the page in which it is located so that when the user goes to another page and returns to the list of clients, it shows the information according to the last status saved in the localstorage. My problem is that when I select a page in the pagination and go to another page when returning to the list, the pagination returns to 1 and I cannot find exactly the reason. I have followed up and apparently when initializing the component it loads the data from the localstorage but then they return to 1. I have created a service to bring the data and save it in the localstorage, I would like to find the reason for this behavior. I have been thinking of placing the information loading logic in the constructor but I think it is better to keep it in the NgOnInit end.
this is mi component:
selector: 'app-cliente-list',
standalone: true,
imports: [NgbPaginationModule, ClienteFiltersComponent, NgForOf, NgIf, FaIconComponent],
providers: [{ provide: ClienteGateway, useClass: ClienteApiService }, ListarClienteUseCase],
templateUrl: './cliente-list.component.html',
styleUrls: ['./cliente-list.component.scss']
})
export class ClienteListComponent implements OnInit {
filtros: any = { nombre: '', tipo_cliente: '', tiene_credito: null };
clientes: Cliente[] = [];
count: number = 0;
current_page: number = 1;
constructor(
private readonly listarClienteUseCase: ListarClienteUseCase,
private readonly toastService: ToastService,
private readonly modalService: NgbModal,
private readonly breadcrumbService: BreadcrumbService,
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly clienteStateService: ClienteStateService
) { }
ngOnInit(): void {
const { filtros, page } = this.clienteStateService.getState();
this.filtros = filtros || this.filtros;
this.current_page = page ?? 1;
this.loadClientes(this.current_page, this.filtros);
this.breadcrumbService.addBreadcrumb({
label: 'Lista de Cliente',
url: this.route.snapshot.url.join('/'),
nivel: 2,
});
}
loadClientes(page: number, filtros: any): void {
this.listarClienteUseCase.execute(page, filtros).subscribe({
next: (response) => {
this.clientes = response.results;
this.count = response.count;
this.current_page = response.current_page;
this.clienteStateService.saveState({ filtros: this.filtros, page: this.current_page });
},
error: (err) => {
this.toastService.error('Error al cargar clientes:', err);
},
});
}
onPageChange(page: number): void {
this.current_page = page;
this.clienteStateService.saveState({ filtros: this.filtros, page: this.current_page });
this.loadClientes(this.current_page, this.filtros);
}
verDetalle(clienteId: number): void {
this.clienteStateService.saveState({ filtros: this.filtros, page: this.current_page });
this.router.navigate(['/clientes', clienteId]);
}
trackByClienteId(index: number, cliente: Cliente): number {
return cliente.id;
}
openFiltrosCliente(content: TemplateRef<any>) {
const modalRef = this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title', scrollable: true, size: 'lg' });
modalRef.result.then((filtros: any) => {
if (filtros) {
this.filtros = filtros;
this.current_page = 1;
this.loadClientes(this.current_page, this.filtros);
}
}, (reason) => {
console.log('Modal cerrado:', reason);
});
}
}
and this is my service
@Injectable({
providedIn: 'root'
})
export class ClienteStateService {
private readonly stateKey = 'clienteListState';
constructor() { }
saveState(state: { filtros: any; page: number }): void {
localStorage.setItem(this.stateKey, JSON.stringify(state));
}
getState(): { filtros: any; page: number } {
const storedState = localStorage.getItem(this.stateKey);
if (storedState) {
return JSON.parse(storedState);
}
return { filtros: { nombre: '', tipo_cliente: '', tiene_credito: null }, page: 1 };
}
clearState(): void {
localStorage.removeItem(this.stateKey);
}
}
I appreciate any help you can give me, thank you very much.