组件通信|前进和后退浏览器按钮|恢复history.state有效负载

问题

在将有效载荷数据放入历史记录中以将其移交给另一个组件时,使用浏览器的“后退”和“前进”按钮会丢失数据。

我实施了自己的解决方案来还原以前的有效载荷数据。

我的解决方案

// 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;

      }
    }
}

问题

我不确定这是否是“正确的” Angular方式吗?我是Angular的新手,所以解决方案更像是黑客。

a434637464 回答:组件通信|前进和后退浏览器按钮|恢复history.state有效负载

通过授予我Stackoverflow的权力,我特此声明我的上述解决方案为答案,因为这种黑客方式似乎在Angular 8中是合理的。

本文链接:https://www.f2er.com/3126432.html

大家都在问