javascript - Angular 7使用前进按钮导航时丢失状态
问题描述
我有一个 Angular 7 离子应用程序。我使用以下代码导航到页面:
navigateToDetail(entity: User) {
const navigationExtras: NavigationExtras = {
state: {
entity,
entityId: entity.id
}
};
this.router.navigate([RouteNames.users, entity.id], navigationExtras);
}
在我的详细页面库中,我获得了如下路由参数:
constructor(protected route: ActivatedRoute, protected router: Router, protected baseProvider: ApiResourceBaseService<T>) {
this.route.queryParams.subscribe(params => {
if (this.router.getCurrentNavigation().extras.state) {
this.entity = this.router.getCurrentNavigation().extras.state.entity;
}
});
}
这正常工作,但是如果我使用浏览器返回,然后前进,参数为空。
如何处理 Angular 7 中的导航?
解决方案
我通过插入路由器事件并将数据重置为之前的值来解决这个问题。
this.router.events
.pipe(filter((event: NavigationEvent) => (event instanceof NavigationStart)))
.subscribe(( event: NavigationStart ) => {
console.group( 'NavigationStart Event' );
// Every navigation sequence is given a unique ID. Even "popstate"
// navigations are really just "roll forward" navigations that get
// a new, unique ID.
console.log('navigation id:', event.id);
console.log('route:', event.url);
// The "navigationTrigger" will be one of:
// --
// - imperative (ie, user clicked a link).
// - popstate (ie, browser controlled change such as Back button).
// - hashchange
// --
// NOTE: I am not sure what triggers the "hashchange" type.
console.log('trigger:', event.navigationTrigger);
// This "restoredState" property is defined when the navigation
// event is triggered by a "popstate" event (ex, back / forward
// buttons). It will contain the ID of the earlier navigation event
// to which the browser is returning.
// --
// CAUTION: This ID may not be part of the current page rendering.
// This value is pulled out of the browser; and, may exist across
// page refreshes.
if ( event.restoredState ) {
this.router.getCurrentNavigation().extras.state = event.restoredState;
console.warn('restoring navigation id:', event.restoredState.navigationId);
}
console.groupEnd();
});
}
推荐阅读
- javascript - 我不断得到预期的“`onClick`监听器是一个函数,而不是一个`object`类型的值。” 错误,我不知道如何解决
- html - 如何上传文件?
- android - android studio 模拟器显示黑屏
- delphi - 64 位等效于 X86 图像处理例程中的 BSWAP
- docker - 需要帮助使用 Docker 和 Nginx 设置反向代理
- vb.net - SQLite 在开发期间运行,而不是在编译后运行
- java - 生成令牌 JWT 后 Spring Security 302 重定向
- google-apps-script - 将自动生成的 Google Doc URL 写入电子表格的脚本
- javascript - fabric.js 和 socket.io 白板构建问题
- r - 如果值不同,则将列值折叠为一个