【问题标题】:Angular 2 - replace history instead of pushingAngular 2 - 替换历史而不是推送
【发布时间】:2016-12-17 21:01:58
【问题描述】:

如何替换历史记录而不是在 Angular 2 的新路由器 (rc.1) 中推送新的?

例如,我在问题列表中 (/questions) 在新路线中打开新模式 (/questions/add),添加新问题后,我转到问题视图 (/questions/1)。如果我回击,我想转到/questions 而不是/questions/add

【问题讨论】:

  • 您是否为您的路线 '/questions/1' 尝试过 'canDeactivate' 守卫?只需检查所需的目的地,如果它是'../add',重定向到'/questions'?或者为 '../add' 路由实现 'canActivate' 代替..
  • 太复杂了。我有数百个地方需要这种行为,而带有重定向的守卫只是会产生大量代码的猴子补丁

标签: angular typescript angular2-routing


【解决方案1】:

【讨论】:

【解决方案2】:

如果你使用

router.navigate

然后

location.replaceState

使用完全相同的路径,您可以触发通常发生的更改,以及替换历史记录。

例如,在您的情况下:

this.router.navigate(['questions/1']);
this.location.replaceState('questions/1');

如果你需要为路由添加参数,你可以使用创建位置的url

router.serializeUrl(router.createUrlTree(/* what you put in your router navigate call */));

在你的例子中:

this.router.navigate(['questions/1', {name:"test"}]);
this.location.replaceState(this.router.serializeUrl(this.router.createUrlTree(['questions/1', {name:"test"}])));

更新

似乎 Angular 路由器现在带有 replace url option。在您的示例中:

this.router.navigate(["questions/1"], {replaceUrl:true});

更新 2

当前有一个issue,在短时间内完成多次导航可能无法正确替换 URL。作为临时解决方法,将导航功能包装在超时中,以使每个功能在单独的循环中触发:

setTimeout(()=>{
    this.router.navigate(["questions/1"], {replaceUrl:true});
});

【讨论】:

  • 注意:对于routerLink 指令,您可以为元素添加replaceUrl 属性以获得相同的效果。
  • 使用router.navigate{ replaceUrl: true } 的唯一警告是它将注册另一个导航事件。如果您正在监听导航事件(例如,NavigationEnd)并且不希望触发两个事件,location.replaceState 会解决问题。
  • 感谢@Jason 提供更新 2 并指定我们在 Angular 中遇到的问题。它能够通过使用 setTimeout() 在 Angular 6 中解决我的问题。
  • 请注意,{replaceUrl: true} 也可作为router.createUrlTree() 的额外选项使用,这意味着您可以在从CanActivate 保护返回Observable<UrlTree> 时使用它(而不必求助于显式路由器导航)。
猜你喜欢
  • 2019-04-10
  • 2017-01-13
  • 1970-01-01
  • 2013-10-01
  • 2019-10-29
  • 2019-01-16
  • 2012-07-27
  • 2021-04-11
相关资源
最近更新 更多