Created
January 27, 2022 00:08
-
-
Save davehasagithub/fbf60b9809833a597c63e89b7c47a848 to your computer and use it in GitHub Desktop.
As tweaked from https://semanticbits.com/route-history-service-in-angular/ and https://github.com/semanticbits/previous-url-example/blob/master/src/app/services/router-history.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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