问题
在将有效载荷数据放入历史记录以将其移交给另一个组件时,使用浏览器的后退和前进按钮会丢失数据。
我实现了自己的解决方案以恢复以前的有效载荷数据。
我的解决方案
// 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的新手,所以解决方案更像是黑客。
[通过授予我Stackoverflow的权力,我在此声明我的上述解决方案作为答案,因为这种黑客方式似乎在Angular 8中是合理的。