Skip to content

Instantly share code, notes, and snippets.

@davehasagithub
Created January 27, 2022 00:08
Show Gist options
  • Save davehasagithub/fbf60b9809833a597c63e89b7c47a848 to your computer and use it in GitHub Desktop.
Save davehasagithub/fbf60b9809833a597c63e89b7c47a848 to your computer and use it in GitHub Desktop.
export interface RouterHistory {
history: number[];
currentIndex: number;
event: NavigationStart | NavigationEnd;
trigger: 'imperative' | 'popstate' | 'hashchange';
id: number;
idToRestore: number;
}
@Injectable({
providedIn: 'root'
})
export class RouterHistoryService {
private depth = 0;
constructor(
router: Router
) {
router.events
.pipe(
filter(event => event instanceof NavigationStart || event instanceof NavigationEnd),
scan<NavigationStart | NavigationEnd, RouterHistory>(
(acc, event) => {
if (event instanceof NavigationStart) {
return {
...acc,
event,
trigger: event.navigationTrigger,
id: event.id,
idToRestore:
(event.restoredState && event.restoredState.navigationId) || undefined
};
}
const history = [...acc.history];
let currentIndex = acc.currentIndex;
if (acc.trigger === 'imperative') {
history.splice(currentIndex + 1);
history.push(acc.id);
currentIndex = history.length - 1;
}
if (acc.trigger === 'popstate') {
const idx = history.findIndex(x => x === acc.idToRestore);
if (idx > -1) {
currentIndex = idx;
history[idx] = acc.id;
} else {
currentIndex = 0;
}
}
return {
...acc,
event,
history,
currentIndex
};
},
{
event: null, history: [], trigger: null, id: 0, idToRestore: 0, currentIndex: 0
}
),
filter(
({event, trigger}) => event instanceof NavigationEnd && !!trigger
)
)
.subscribe(({currentIndex}) => {
this.depth = currentIndex;
console.log('*** depth:' + this.depth);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment