After experimenting with various solutions that were available-
this.router.navigated
consistently returned true
unexpectedly (possibly due to navigating to another page using redirectTo
in routing).
- I attempted to use
history.length
, but it always yielded a value of 2.
- Next, I explored the option of utilizing
history.state
to determine if any arbitrary data was present, indicating a fresh tab without history. However, this only set {navigationId: 1}
(by Angular), making it ineffective for refreshing an existing tab with previous history.
Ultimately, I devised a solution using sessionStorage
that proved to be effective for my scenario.
In a global context (specifically in app.component.ts
), I implemented the following-
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());
});
}
When checking for history before navigating back, I utilize this approach-
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')
}
}