Skip to content
Advertisement

When should I set localStorage in Angular?

I have a list of employee list on EmployeesComponent and there is “Education Overview” and “Salary Overview” buttons for each records. When I click one of the overview button it goes to the OverviewComponent first and then load the correponding component (salary or education) into this OverviewComponent. There is also a “Back” button on each of these salary and education components. The structure is as shown on the following image:

components

The problem is that: When I come back to the EmployeesComponent, I need to reload the paging params e.g. the last page number before navigating to the overview pages. For this I use localStorage and check the saved value on each page load of the 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
}

But I save the page params on the OverviewComponent so that use a single place for salary and education pages. I think it is not a good approach and it may cause the localStorage items to be mixed as they use the same key (for some reason I need to use the same key sometimes).

So, should I set the paging parameters just before navigating to the overview page in the EmployeesComponent? And then check them on loading EmployeesComponent? What is a proper way for this scenario?

Advertisement

Answer

You can use the query-params in routing. So now when you redirect from employess component to overViewComponent, then based on click i.e., Education Overview or Salary Overview just send the query params with the url.

Then now when you get back to employess component, just use the query params value you get in overView component and you can get the information you want back in employess component.

Q- what is the most proper place for adding and removing paging items to local storage

A- Most proper place for adding and removing localstorage item is where it get’s change. In your case, just set localstorage in overView component where you are getting params ( this.activateRoute.params() ) inside this function. And remove the localstorage on ngOnInit function of employee component.

Advertisement