Angular 7 Router - 导航而不添加到历史记录

Ale*_*ork 15 javascript history router angular

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

this.router.navigateByUrl(`${pathWithoutFragment}#${newFragment}`);
Run Code Online (Sandbox Code Playgroud)

我可以只用 Angular 来做吗?

Elr*_*ron 24

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

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

this.router.navigate([`/somewhere`], { replaceUrl: true });
Run Code Online (Sandbox Code Playgroud)

这样,当您按回时,它就不会记住历史记录中的上一页。


Che*_*pan 5

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

 this.router.replaceUrl('path')
Run Code Online (Sandbox Code Playgroud)

跳过位置更改

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

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

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

  • 不,它取代了状态。这意味着 URL 将在地址栏中更新,但堆栈中没有新事件,因此单击后退按钮会导致与没有导航时相同的上一页。如果您使用skipLocationChange,您也会有这种效果,但地址栏中的URL 不会更新。 (3认同)
  • 我认为 replaceUrl 是这里的正确答案。skipLocationChange 也不会更新 URL,这听起来不像 OP 想要的。 (2认同)