Home > other >  Angular: How to remove localstorage when user moves from one module to another module
Angular: How to remove localstorage when user moves from one module to another module

Time:10-05

I have couple of modules in my angular application. Claim module is one of the module and in one of the component of claim module, I have to filter claims with various search options. The ask is to persist the search option selected, once user moves to other claim components. But the tricky part is, those search options should clear out once the user moves to another module. Now usually, I can simply put search options to localstorage. But localstorage will persist data across modules. So even though user moves to another module and comes back to claim module, search options will be still there in localstorage. So my question is, is there a way, I can clear the search option saved in localstorage, once user moves from claim module to another module.

CodePudding user response:

You could inject the Router in your claims component and subscribe to the events. This way you can check if the new route is not part of the claim module and clear the local storage:

  constructor(private router: Router) {}

  ngOnInit() {
    this.router.events
      .pipe(
        filter((e) => e instanceof NavigationEnd && !e.url.startsWith('claim')),
        first()
      )
      .subscribe(() => {
        localStorage.removeItem('claims');
      });
  }

CodePudding user response:

Try to pass data through ׳routes׳ like this:

{path : 'heroes', component : HeroDetailComponent, data : {clearLocal : true}}

Then you can listen to the data and remove class - for exemple in app-component

  • Related