我什么时候应该在 Angular 中设置 localStorage?
When should I set localStorage in Angular?
我在 EmployeesComponent
上有一份员工列表,每条记录都有“教育概览”和“薪资概览”按钮。当我单击其中一个概览按钮时,它首先转到 OverviewComponent
,然后将相应的组件(工资或教育)加载到此 OverviewComponent
。这些工资和教育组成部分中的每一个都有一个“后退”按钮。结构如下图所示:
components
问题是:当我回到 EmployeesComponent
时,我需要重新加载分页参数,例如导航到概览页面之前的最后页码。为此,我使用 localStorage
并在 EmployeesComponent
.
的每个页面加载时检查保存的值
searchParams: any;
ngOnInit() {
let searchParams = JSON.parse(localStorage.getItem('routeParams'))?.searchParameters;
if(searchParams){
this.searchParams = searchParams;
window.localStorage.removeItem('routeParams'); // remove routeParams from localStorage
// load list using this.searchParams
}
但我将页面参数保存在 OverviewComponent
上,以便工资和教育页面使用一个位置。我认为这不是一个好方法,它可能会导致 localStorage 项混合使用,因为它们使用相同的密钥(出于某种原因,有时我需要使用相同的密钥)。
那么,我是否应该在导航到 EmployeesComponent
中的概览页面之前设置分页参数?然后在加载 EmployeesComponent
时检查它们?这种情况的正确方法是什么?
您可以在路由中使用查询参数。
所以现在当你从 employess component
重定向到 overViewComponent
时,然后基于点击,即 Education Overview 或 Salary Overview 只是使用 url.
发送查询参数
那么现在当你回到 employess component
时,只需使用你在 overView component
中获得的查询参数值,你就可以在 employess component
中获得你想要的信息。
Q- 在本地存储中添加和删除分页项最合适的位置是什么
A- 添加和删除 localstorage 项目最合适的地方是它发生变化的地方。
在您的情况下,只需在 overView 组件中设置 localstorage,您将在此函数中获取参数( this.activateRoute.params() )。并在employee组件的ngOnInit函数中移除localstorage。
我在 EmployeesComponent
上有一份员工列表,每条记录都有“教育概览”和“薪资概览”按钮。当我单击其中一个概览按钮时,它首先转到 OverviewComponent
,然后将相应的组件(工资或教育)加载到此 OverviewComponent
。这些工资和教育组成部分中的每一个都有一个“后退”按钮。结构如下图所示:
components
问题是:当我回到 EmployeesComponent
时,我需要重新加载分页参数,例如导航到概览页面之前的最后页码。为此,我使用 localStorage
并在 EmployeesComponent
.
searchParams: any;
ngOnInit() {
let searchParams = JSON.parse(localStorage.getItem('routeParams'))?.searchParameters;
if(searchParams){
this.searchParams = searchParams;
window.localStorage.removeItem('routeParams'); // remove routeParams from localStorage
// load list using this.searchParams
}
但我将页面参数保存在 OverviewComponent
上,以便工资和教育页面使用一个位置。我认为这不是一个好方法,它可能会导致 localStorage 项混合使用,因为它们使用相同的密钥(出于某种原因,有时我需要使用相同的密钥)。
那么,我是否应该在导航到 EmployeesComponent
中的概览页面之前设置分页参数?然后在加载 EmployeesComponent
时检查它们?这种情况的正确方法是什么?
您可以在路由中使用查询参数。
所以现在当你从 employess component
重定向到 overViewComponent
时,然后基于点击,即 Education Overview 或 Salary Overview 只是使用 url.
那么现在当你回到 employess component
时,只需使用你在 overView component
中获得的查询参数值,你就可以在 employess component
中获得你想要的信息。
Q- 在本地存储中添加和删除分页项最合适的位置是什么
A- 添加和删除 localstorage 项目最合适的地方是它发生变化的地方。 在您的情况下,只需在 overView 组件中设置 localstorage,您将在此函数中获取参数( this.activateRoute.params() )。并在employee组件的ngOnInit函数中移除localstorage。