Tried many solutions out there-
this.router.navigated
always returned true
for some reason (maybe because I'm navigating to another page via redirectTo
in routing).
- I tried with
history.length
but that always returned 2.
- Then tried to use
history.state
to check if doesn't contain any arbitrary data, then I can assume it's a fresh tab open without any history. But it was only setting {navigationId: 1}
(by Angular) so was not useful when refreshing an existing tab with existing history.
Finally, I thought of using sessionStorage
this way which is working fine for me.
In a global space (let's say in app.component.ts
), I did this-
ngOnInit(): void {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
).subscribe(() => {
let navigations = parseInt(sessionStorage.getItem('totalNavigations'), 10) || 0;
navigations++;
sessionStorage.setItem('totalNavigations', navigations.toString());
});
}
Now, when I want to go back to see if there is any history, I'm doing this-
goBack(): void {
const totalNavigations = parseInt(sessionStorage.getItem('totalNavigations'), 10);
if (totalNavigations > 1) {
this.location.back(); // Or history.back()
} else {
this.router.navigateByUrl('/my-default-path')
}
}