import { Injectable } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; import { filter } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class NavigationService { private readonly CURRENT_URL_KEY = 'currentUrl'; private readonly PREVIOUS_URL_KEY = 'previousUrl'; currentUrl: string | null; previousUrl: string | null; constructor(private router: Router) { this.currentUrl = sessionStorage.getItem(this.CURRENT_URL_KEY); this.previousUrl = sessionStorage.getItem(this.PREVIOUS_URL_KEY); this.router.events .pipe(filter((event): event is NavigationEnd => event instanceof NavigationEnd)) .subscribe((event) => { const newUrl = event.urlAfterRedirects; // Ignore duplicate events if (newUrl === this.currentUrl) { return; } this.previousUrl = this.currentUrl; this.currentUrl = newUrl; if (this.previousUrl) { sessionStorage.setItem(this.PREVIOUS_URL_KEY, this.previousUrl); } sessionStorage.setItem(this.CURRENT_URL_KEY, this.currentUrl); }); } canGoBack(): boolean { return !!this.previousUrl; } back(fallbackUrl = '/'): void { if (this.canGoBack()) { window.history.back(); } else { this.router.navigateByUrl(fallbackUrl); } } }