0

I want to clear Localstorage data on browser back button click. But how to detect browser back button click in Angular2. I am not getting any exact solution. Can anyone please tell me how to do this?

ananya
  • 1,001
  • 6
  • 33
  • 50
  • There is a difference if you navigate back within the page (undo a route navigation) and navigating back to a different page. What are you interested in? "I am not getting any exact solution." Your question should demonstrate what you tried and why you didn't get the expected result and what the expected result is. – Günter Zöchbauer Sep 11 '17 at 09:56
  • Browser back button means obviously it ll redirect to a different page.And I am not getting any solution for that.@GünterZöchbauer – ananya Sep 11 '17 at 09:59
  • That's not obvious at all. If you navigate between angular routes and then back, you're always on the same page, until you go as far back using the back button until you reached the initial state and then the next back button click navigates away from the application and to the previous application or page. – Günter Zöchbauer Sep 11 '17 at 10:03
  • I think what you're looking for is https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser/37642657#37642657 (see also https://stackoverflow.com/questions/40468267/angular-2-does-ngondestroy-get-called-on-refresh-or-just-when-navigate-away-fr/40468409#40468409) – Günter Zöchbauer Sep 11 '17 at 10:04
  • @Dheeraj Kumar 's answer is working for me.Thank you for your time.@GünterZöchbaue – ananya Sep 11 '17 at 10:08

1 Answers1

1

You can use ngOnDestroy method of components which is part of component life cycle.

This component is called whenever component is destroyed.

What you can do is create a service where your logic to clean localstorage will be written.

Call this service on ngOnDestroy method of your component.

remember to import {OnDestroy} from '@angular/core' and add OnDestroy to the implements section of your Class definition

Hope this helps.

Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80