【问题标题】:Angular2 Pending change guard, need to ignore specific route params when re-navigating to current routeAngular2 Pending change guard,重新导航到当前路由时需要忽略特定的路由参数
【发布时间】:2017-04-28 02:39:44
【问题描述】:

我有一个像

这样的未决变更守卫
    import {CanDeactivate} from '@angular/router';

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
      // when navigating away from your angular app, the browser will show a generic warning message
      // see http://stackoverflow.com/a/42207299/7307355
      confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
  }
}

我的问题是我还有一些与页面路由参数相关联的选项卡控件,因此当导航一个选项卡时,它会更新路由参数,反之亦然。它通过使用新参数导航到当前路由来更新参数,新参数不会重新加载组件,因为它仍然是当前路由。我的问题是我不希望 PendingChangesGuard 将这些路由更改视为停用,因为该组件仍在页面上的不同选项卡中。

理想情况下,我可以将一些参数传递给守卫,告诉它在重新导航到当前路线的情况下要忽略哪些路线参数,然后以某种方式在守卫内检测是否唯一的变化是其中之一被忽略的参数。我不确定如何检测这样的参数变化和想法?

【问题讨论】:

  • 您可以访问canDeactivate 中的路由参数,您可以直接使用它来构建您的逻辑`canDeactivate(component: ComponentCanDeactivate, route: ActivatedRouteSnapshot,state: RouterStateSnapshot)。
  • 我知道这一点,但是如何查看之前的路线和当前路线并找出哪些参数发生了变化?

标签: angular angular2-routing angular2-router


【解决方案1】:

您可以使用查询参数而不是路由参数。查询参数不会导致守卫重新运行。这不是查询参数和路由参数(或矩阵参数,或其他名称)之间的唯一区别,但这让它们值得考虑。角度路由器非常固执己见,因此您可能永远找不到优雅的解决方案。

查询参数:

this.router.navigate([], {
  queryParams: {'tab': whatever}
});

<a [routerLink]="[]" [queryParams]="{'tab': whatever}">tab</a>

【讨论】:

  • 谢谢!我曾考虑过使用查询字符串,但过去我在卸载组件时遇到了清理它们的问题,最终出现了孤立的查询字符串,或者新路由正在添加查询字符串而卸载的路由正在清理它的时间问题查询字符串,它们会干扰。路由参数至少在这方面保持简单。
  • 我记得大约一年前这样的事情,当时在导航中“保留”查询参数是默认行为(现在不再是)。这就是你在说的吗?当然,如果您同时使用查询参数有多个路由,那么这是一个坏主意。我对选项卡使用查询参数,仅此而已。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 2017-12-21
  • 2018-06-08
  • 2017-05-07
  • 2015-10-25
  • 2019-10-27
  • 2023-03-06
相关资源
最近更新 更多