角度 7 使用前进按钮导航时丢失状态



我有一个角度 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;
}
});
}

这通常工作正常,但是如果我使用浏览器返回然后继续,则参数为空。

如何处理角度 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();
});
}

相关内容

  • 没有找到相关文章

最新更新