What is a proper way to preserve parameters after navigating back?

Tags: , , , ,



In my Angular app, I have list and details pages and I want to lkeep the pageIndex value before navigating to details page. There is a Back button in the details page and I can return the list page by clicking on that button. However, I want to get the pageIndex value when navigating back to the list page and let the user open the page where he/she was before. For example I navigate 3rd page on the list and click details. At this stage I set the pageIndex to 3 and then navigate to details. Then by clicking the Back button I can navigate back to the list page, but I need to retrieve the pageIndex as 3.

So, what is an elegant way to fix this problem in Angular 10+?

list-componnet

details(id) {
    this.router.navigate(['/details'], { state: { id: id } }); // I pass id value of the record
}

details-componnet

constructor(private router: Router) {
    this.id = this.router.getCurrentNavigation().extras.state.id;
}

back() {
    this._location.back();
}

Answer

Just write a simple example to make it work, I use the sessionStorage and router together, use router to show your the routing module, actually you can just use sessionStorage only, and wrapper it in a servive. Then you can retrieve the pageIndex anywhere.

And if you want to use router only, the pageIndex paramater will be place in both list and detail component, since this two component all need to use this value, in list component you will need pageIndex to set data-table, in detail component you need this value to pass to list component when redirect back triggered.

The routing module like below:

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { ListComponent } from "./list/list.component";
import { DetailComponent } from "./detail/detail.component";

const routes: Routes = [
  { path: "", redirectTo: "list", pathMatch: "full" },
  {
    path: "list/:pageIndex=1",
    component: ListComponent,
    pathMatch: "full"
  },
  {
    path: "detail/:id",
    component: DetailComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Here you can navigate to list page from detail page use:

this.router.navigate(["/list/" + pageIndex]);

And then in list page’s ngOnInit method to set current pageIndex to your data-table. Here is the demo: https://stackblitz.com/edit/angular-ivy-5vmteg?file=src/app/list/list.component.ts



Source: stackoverflow