2

I need to keep applied filters. When I change components or when I return to the previous component, I would like the filters to be applied already (stay the same). I need to add a function to save the filter parameters in localStorage and a function to read these parameters. Can anyone help?

D Malan
  • 10,272
  • 3
  • 25
  • 50
Aleksandar
  • 63
  • 1
  • 6
  • 1
    Possible duplicate of [How to store token in Local or Session Storage in Angular 2?](https://stackoverflow.com/questions/39840457/how-to-store-token-in-local-or-session-storage-in-angular-2) – Akber Iqbal Jul 24 '19 at 08:53

3 Answers3

5

You can just use the LocalStorage like so:

localStorage.setItem('componantAFilters', JSON.stringify(filterObj))

localStorage.getItem('componantAFilters')

My suggestion is to call getItem in ngOnInit and setItem in ngOnDestroy

for more information: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Yonatan Lilling
  • 298
  • 1
  • 4
  • 13
0

In order to save the the filter parameters in local storage :

import { SESSION_STORAGE, WebStorageService } from 'angular-webstorage-service';

then in the constructor of the same component:

constructor(@Inject(SESSION_STORAGE) private storage: WebStorageService) {
  this.storage.set('filters', JSON.stringify(this.filters));
}

and in ordrer to get these filters:

this.storage.get('filters');
S.Voulgaris
  • 184
  • 1
  • 4
0

Although the answer given by @S.Voulgaris and @Yonatan Lilling may work to an extent, but it has its drawbacks. Following the approach of saving all filters in a localstorage and then retrieving those filters, then applying to the component, writing restore logic is cumbersome.

A better approach would be to cache the older component/route and show from the cache. Angular does have native support for this starting from version 2.3.

Angular creates a RouteStateSnapshot every time when the redirect is applied after navigation. RouteStateSnapshot is an immutable object that stores ActivatedRouteSnapshots tree. Please read about it if you are not aware. When we navigate to the new page or just change a URL parameter we get new RouteStateSnapshot.

RouteReuseStrategy is the angular way to customize when Angular should reuse route snapshots or in simpler words when the page should be reused(no more manual restore, http call involved).

create a class MyRouteReuseStrategy extending RouteReuseStragy

export class MyRouteReuseStrategy implements RouteReuseStrategy { 

    private states: {[key: string]: DetachedRouteHandle} = {};

    constructor() {

    }

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.states[route.url.join("/") || route.parent.url.join("/")] = handle;    
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!this.states[url];    
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return this.states[route.url.join("/") || route.parent.url.join("/")];    
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot):boolean {
       return future.routeConfig === curr.routeConfig;
    }
}

And then in your App Module use this as a provider

@NgModule({
[...],
providers: [
    {provide: RouteReuseStrategy, useClass: MyRouteReuseStrategy }
]
)}
export class AppModule {
}

That's all about it. You can customize the methods of MyRouteReuseStrategy class according to your application needs( you may not want to cache some component like logout or a page that shows realtime data etc).