Angular - 如何在不修改历史记录的情况下更改 url

问题描述 投票:0回答:1

我想更改我的页面的 url,但不更改角度历史状态或重新加载页面。

这有可能吗?

已经试过了

方法 没有历史变化 不重新加载 更改网址
location.replaceState(url)
不工作 工作 工作
router.navigateByUrl(url, {skipLocationChange: true, })
工作 不工作 工作

一点背景

我在 url 的开头添加了

/de
-> 所以从
/my-url
/de/my-url
.

但实际上,现有路线是

/my-url
所以为了通过我的应用程序导航,我添加了一个守卫。

  1. 控制网址
  2. 如果它确实有
    /de
    删除它和
    router.navigate(urlWithoutDe)
  3. 再次添加回来以直观地看到
    /de
    (或任何其他语言,如
    /en
    /fr
    ,...)
  4. 但是当用户使用后退按钮向后导航时,
    guard
    不会被触发,所以它会尝试导航到不存在的
    /de/my-url
    ..
angular angular-routing angular-router window.location
1个回答
0
投票

你有没有试过在你的

beforeunload
中收听
app.component
事件,像这样:

@Component({ 
    selector: 'app-root',
    ..
)}
class AppComponent {
    @HostListener('window:beforeunload')
    navigateToActualUrl() {
        // detect if the user is trying to load an invalid URL
        // not sure if location contains the "wrong" URL at this point
    }
}

https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent

一般来说,当用户点击后退/前进按钮时,Angular Guards 不会被触发,你需要监听这个事件。

© www.soinside.com 2019 - 2024. All rights reserved.