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?
Asked
Active
Viewed 3,076 times
0
-
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 Answers
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.

IveMadeAHugeMistake
- 79
- 1
- 10

Dheeraj Kumar
- 3,917
- 8
- 43
- 80
-
5I doubt `ngOnDestroy` is called when the back button navigates away from the application. – Günter Zöchbauer Sep 11 '17 at 09:56
-
It is sir. As soon as current application is closed or navigated to another application. – Dheeraj Kumar Sep 11 '17 at 09:58
-
4I'm sure it isn't, because this is the same for the application as closing the tab where `ngOnDestroy` also isn't called. I don't know how to reproduce in Plunker though. – Günter Zöchbauer Sep 11 '17 at 10:02
-
Thank you so much @Dheeraj Kumar.It is working for me.You saved my day.:):) – ananya Sep 11 '17 at 10:03
-