首页 > 解决方案 > 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 中的导航?

标签: javascriptangulartypescriptionic-frameworknavigation

解决方案


我通过插入路由器事件并将数据重置为之前的值来解决这个问题。

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();
        });
}

推荐阅读