Problem
On placing payload-data in the history to hand it over to another component, the data is lost on using the browser's Back and Forward buttons.
I implemented my own solution to restore previous payload-data.
My solution
// some.component.ts
//
// navigate and set payload in arbitrary component
this.router.navigate(['/course/create'], {
state: { payload: cid }
});
// app.component.ts
//
// restore payload on using Back and Forward buttons
private historyStateCache = [];
ngOnInit() {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// SAVE CURRENT HISTORY
const state = JSON.parse(
JSON.stringify(this.router.getCurrentNavigation().extras.state || {})
);
this.historyStateCache[event.id] = state;
// PROCESS BACK AND FORWARD BUTTONS
if (event.restoredState) {
const targetId = event.restoredState.navigationId;
this.router.getCurrentNavigation().extras.state = this.historyStateCache[targetId];
// SAVE CURRENT HISTORY
const stateX = JSON.parse(
JSON.stringify(this.router.getCurrentNavigation().extras.state)
);
this.historyStateCache[event.id] = stateX;
}
}
}
Question
I am unsure if this is the 'correct" Angular way? I am new to Angular and the solution feels more like a hack.