Reputation: 1274
I have a problem handling the back button , when the user taping the back button the ngOnInit is not triggered and the component is not working as wanted . from what i saw i understand that when taping back its only make the ngOnDestroy fire but not the ngOnInit
this is the lifecycle
open App --> ngOnInit() called
click on some anther component --> ngOnInit() of the new component called
tap back --> ngOnDestroy
Did someone had the same problem and how did you handle it ? thank you
Upvotes: 3
Views: 2071
Reputation: 1274
After some search i decided to use this solution
in components that i need the ngOnInit to run even if the navigate is from the back button or function i added this
constructor(private location : PlatformLocation) {}
ngOnInit() {
this.location.onPopState(() => {
this.initComponent();
});
}
Upvotes: 4
Reputation: 148534
Why do you think ngOnInit
should run on back ? it doesn't
Solution is to use router events :
For example : A Solution to detect back
from "/beatles/john/songs/strawberryfields"
to "/doors/jim/girlfriend/pam"
Doors page --------> Beatles page.....(back tapped)----------->Doors
Is :
Add this method into a shared service :
public onNavigatePreviousToCurrent(pre: string, current: string ): Observable<any>
{
return this.router.events.pipe(filter(e => e instanceof NavigationEnd), pairwise(), filter((f: [any, any]) =>
{
return f[0].url.toLowerCase()
.indexOf(pre.toLowerCase()) > -1 &&
f[1].url.toLowerCase()
.indexOf(current.toLowerCase()) > -1;
}) );
}
In the Doors page call it :
ngOnInit()
{
let f = this._routingService.onNavigatePreviousToCurrent("john", "pam") //or doors or jim
.subscribe((res) =>
{
//do what you want here !!!
}, (error) =>
{
});
//don't forget to unsubscribe `f`
}
Notice that you can use any token from /beatles/john/songs/strawberryfields
( beatles
,john
,songs
,strawberryfields
, atles
)----> also in Doors. (substring)
Basically this methods detects where you came from and what is the destination after back
.
BTW you might want to say : "well , I don't know where I am , I only want a situation where a user tapped "back".
Answer :
this._routingService.onNavigatePreviousToCurrent("/", "pam") ;
// "/" will always be present , so basically this ^ detects back from anywhere to Doors page
Upvotes: 2