最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to save filters in localstorage angular 6? - Stack Overflow

programmeradmin8浏览0评论

I need to keep applied filters. When I change ponents or when I return to the previous ponent, 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?

I need to keep applied filters. When I change ponents or when I return to the previous ponent, 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?

Share Improve this question edited Jul 24, 2019 at 10:28 D Malan 11.5k3 gold badges35 silver badges64 bronze badges asked Jul 24, 2019 at 8:24 AleksandarAleksandar 631 silver badge6 bronze badges 1
  • 1 Possible duplicate of How to store token in Local or Session Storage in Angular 2? – Akber Iqbal Commented Jul 24, 2019 at 8:53
Add a ment  | 

3 Answers 3

Reset to default 5

You can just use the LocalStorage like so:

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

localStorage.getItem('ponantAFilters')

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

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

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 ponent:

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');

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 ponent, writing restore logic is cumbersome.

A better approach would be to cache the older ponent/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 ponent like logout or a page that shows realtime data etc).

发布评论

评论列表(0)

  1. 暂无评论