javascript - Angular 7 使用前进按钮导航时丢失状态

标签 javascript angular typescript ionic-framework navigation

我有一个 Angular 7 ionic 应用程序。我使用以下代码导航到页面:

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 - Angular 7 使用前进按钮导航时丢失状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176386/

相关文章:

javascript - Jquery 数据表在 Internet Explorer 中显示为低亮度

javascript - Angular 垫输入

javascript - 如何从 Angular 2 Meteor 的服务器端检测和注销空闲用户?

angular - 如何在rxjs中开始后停止间隔

javascript - 使用 jQuery 用命名的 id 替换两个 div 标签之间的内容(标签和文本)

angular - 如何动态地将垫错误添加到垫输入字段?

javascript - 有没有办法可以将 Text 组件的全部内容包装在 React-Native 的父 View 中?

javascript - 悬停时的 Jquery 颜色随机化

angular - 另一个进程,id #######,当前正在运行 ngcc

javascript - 当提供服务的组件被破坏时,服务也会被破坏吗?