Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep applied filters on browser back and forward Angular 2

I have product listing page, where I do have all data to show user, if user is applying filters, I am filtering list on client side itself using Angular 2,

Now if user move forward to project details page and click browser back button, all applied filters vanished as it should be, But I need to implement so that on back button all applied filters should persist.

Solutions I am thinking: -

Approach : Whenever User apply filter we add that in URL and redirect.

Problem : On every URL redirect API's will be called.

Is there a better way I can approach this problem ?

like image 710
Arun Tyagi Avatar asked May 26 '16 05:05

Arun Tyagi


2 Answers

Storing things in the URL as arguments is a good approach, since you don't depend on hidden state (global application variables) to build your view.

However I'd not intercept the routing component, but rather use Angular's support for structured URLs and filter the data in the onInit method or whenever it is available.

like image 139
Horia Coman Avatar answered Oct 06 '22 07:10

Horia Coman


If you want the filter criteria being visible in the URL (and to be bookmarkable) use router parameters and redirect to the URL containing the updated parameters. If you use routerCanReuse() { return true; }, then the component is not even reloaded but justrouterOnReuse()` is called where you can acquire the updated parameters.

If you don't want the filter criteria to appear in the URL, use a shared service to store the parameters, then navigating doesn't destroy the parameter values. Ensure that the provider for the service is provide high enough (AppComponent for example) for it to not get destroyed when a component gets destroyed by routing away.

like image 32
Günter Zöchbauer Avatar answered Oct 06 '22 06:10

Günter Zöchbauer