0

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.

Dabbel
  • 2,468
  • 1
  • 8
  • 25

1 Answers1

0

By the powers of Stackoverflow granted to me, I hereby declare my above solution as the answer, as this way of hacking seems to be justified with Angular 8.

Dabbel
  • 2,468
  • 1
  • 8
  • 25