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?
-
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– Günter Zöchbauer2017-09-11 09:56:32 +00:00Commented Sep 11, 2017 at 9:56
-
Browser back button means obviously it ll redirect to a different page.And I am not getting any solution for that.@GünterZöchbauerananya– ananya2017-09-11 09:59:25 +00:00Commented Sep 11, 2017 at 9: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– Günter Zöchbauer2017-09-11 10:03:53 +00:00Commented Sep 11, 2017 at 10:03
-
I think what you're looking for is stackoverflow.com/questions/37642589/… (see also stackoverflow.com/questions/40468267/…)Günter Zöchbauer– Günter Zöchbauer2017-09-11 10:04:28 +00:00Commented Sep 11, 2017 at 10:04
-
@Dheeraj Kumar 's answer is working for me.Thank you for your time.@GünterZöchbaueananya– ananya2017-09-11 10:08:30 +00:00Commented Sep 11, 2017 at 10:08
Add a comment
|
1 Answer
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.
5 Comments
Günter Zöchbauer
I doubt
ngOnDestroy is called when the back button navigates away from the application.Dheeraj Kumar
It is sir. As soon as current application is closed or navigated to another application.
Günter Zöchbauer
I'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.ananya
Thank you so much @Dheeraj Kumar.It is working for me.You saved my day.:):)
Dheeraj Kumar
@ananya I am glad it helped :)