返回后保留参数的正确方法是什么?

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

在我的 Angular 应用程序中,我有列表和详细信息页面,我想在导航到详细信息页面之前保留 pageIndex 值。详细信息页面中有一个后退按钮,我可以通过单击该按钮 return 返回列表页面。但是,我想在导航回列表页面时获取 pageIndex 值,并让用户打开 he/she 之前所在的页面。例如,我浏览列表的第 3 页并单击详细信息。在此阶段,我将 pageIndex 设置为 3,然后导航到详细信息。然后通过单击“后退”按钮,我可以导航回列表页面,但我需要将 pageIndex 检索为 3.

那么,在 Angular 10+ 中解决这个问题的优雅方法是什么?

列表组件

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

详细组件网

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

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

使用 sessionStoragelistService 或路由器 queryParams 来跟踪当前 pageIndex。 我提倡 queryParams,因为它看起来最合乎逻辑,您也可以 link 直接转到特定页面。

constructor(
    private route: ActivatedRoute,
  ) { }
// Access the queryParam in list component
// Ie /list?pageIndex=4
this.route.queryParams.subscribe(params => {
        // Do something with params.pageIndex if it exists
    }
);

我也会考虑改变你处理路由细节的方式。如果到列表的路径是 /list 那么到细节的路径应该是 /list/<listid> 这样你可以 link 如果需要直接到细节。

您可以按如下方式访问 listId 参数,但请注意,它还必须在路由器定义中指定为参数。

// Router definition
{ path: 'list/', component: ListComponent},
{ path: 'list/:listId', component: ListIdComponent}
// Access the listId in the details component
this.route.params.subscribe(param=> {
    // Do somthing with param.listId
});

写一个简单的例子让它工作,我把sessionStorage和router一起使用,用router给你展示路由模块,实际上你可以只使用sessionStorage,然后把它包装在一个servive中。然后你可以在任何地方检索 pageIndex。

如果你只想使用router,pageIndex参数将同时放在list和detail组件中,因为这两个组件都需要使用这个值,在list组件中你需要pageIndex来设置数据-table,在详细组件中,当重定向返回触发时,您需要将此值传递给列表组件。

路由模块如下:

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 {}

在这里您可以从详细信息页面导航到列表页面使用:

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

然后在列表页面的ngOnInit 方法中将当前pageIndex 设置为您的数据-table。这是演示:https://stackblitz.com/edit/angular-ivy-5vmteg?file=src/app/list/list.component.ts