首页 > 解决方案 > 在 Angular 路由中使用 replaceUrl 以省略浏览器历史记录中的重定向

问题描述

假设我有这些 Angular 11 路线:

{
  path: 'wizard',
  children: [
    { path: 'step1', component: Step1Component },
    { path: 'step2', component: Step2Component },
    { path: 'step3', component: Step3Component },
    { path: '**', redirectTo: 'step1' },
  ]
}

现在,如果我导航到http://localhost:4200/wizard/incorrectpath我会被重定向到http://localhost:4200/wizard/step1哪个是完美的。但是,第一个不正确的路径确实会成为浏览器历史记录的一部分。

当我使用主动路由命令时,我可以:

this.router.navigate(['wizard', 'step1'], { replaceUrl: true });

这可确保在浏览器历史记录中替换原始路由。这可以确保如果用户使用“返回”,他们不会降落在再次将他们“向前”重定向的路线上。

你能以某种方式使用replaceUrl或类似的Route吗?

Route接口似乎没有该属性。我目前的解决方法是使用redirectTo,而是使用一个完整的组件来进行主动路由,.navigate(...)但我想避免这种情况,因为它更加冗长。

标签: angulartypescriptangular-routing

解决方案


推荐阅读