【问题标题】:Angular 7 Router - Navigate without adding to the historyAngular 7 路由器 - 导航而不添加到历史记录
【发布时间】:2019-05-29 20:34:28
【问题描述】:

使用 Angular 路由器,我想导航到另一个 url 而不将其添加到浏览器历史记录中。

this.router.navigateByUrl(`${pathWithoutFragment}#${newFragment}`);

我可以只使用 Angular 吗?

【问题讨论】:

    标签: javascript angular router history


    【解决方案1】:

    正如@IngoBürk 在评论中提到的,您可以在不使用skiplocationChange 的情况下获得相同的结果

     this.router.replaceUrl('path')
    

    skipLocationChange

    在不将新状态推入历史的情况下进行导航。

    this.router.navigateByUrl([`${pathWithoutFragment}#${newFragment}`], { skipLocationChange: true });
    

    参考:https://angular.io/api/router/NavigationExtras#skipLocationChange

    【讨论】:

    • 我认为 replaceUrl 是这里的正确答案。 skipLocationChange 也不会更新 URL,听起来这不是 OP 想要的。
    • 我看不出您的编辑与我的评论有什么关系?我的意思是使用replaceUrl 而不是skipLocationChange。也是NavigationExtras的一个选项。
    • 不,它取代了状态。这意味着 URL 将在地址栏中更新,但堆栈上没有新事件,因此单击后退按钮会导致与没有导航的相同页面。如果你使用skipLocationChange,你也有这个效果,但是地址栏中的URL不会更新。
    • 您的新编辑仍然错误。同样,您需要使用 replaceUrl。现在您刚刚编辑为完全不使用标志,这是一个正常的导航。我现在将不再试图解释这一点,我认为这已经很清楚了......
    【解决方案2】:

    感谢NavigationExtras,您现在可以在navigate() 中使用replaceUrl: boolean

    这将替换当前的url,新的url会在地址栏中更新:

    this.router.navigate([`/somewhere`], { replaceUrl: true });
    

    这样当你按返回时它就不会记住历史中的上一页了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2020-03-22
      相关资源
      最近更新 更多