Location.go()之后,History.back()不会触发ActivatedRoute.paramMap

Tim*_*Tim 2 browser-history angular-routing angular

考虑这个网址:

http://localhost:4200/items

当在 GUI 中打开(展开)元素时,我使用Location.go() 来更新 URL :

http://localhost:4200/items;openedId=123
Run Code Online (Sandbox Code Playgroud)

当我点击后退按钮时,URL 更改回http://localhost:4200/items,但我对 ActivatedRoute.paramMap 的订阅未触发。(因此我的物品保持打开状态)

奇怪的是,当我连续打开两个元素,然后回击两次时,就会触发它:

Open main page -> http://localhost:4200/items
Open item 123  -> http://localhost:4200/items;openedId=123
Open item 456  -> http://localhost:4200/items;openedId=456

Back to http://localhost:4200/items;openedId=123 -> ActivatedRoute.paramMap triggered
Back to http://localhost:4200/items -> ActivatedRoute.paramMap triggered (!)
Run Code Online (Sandbox Code Playgroud)

为什么第一次不触发?为什么我需要有两个历史记录才能工作?我很困惑。

更新:这是我监听 paramMap 中的更改的方式:

  public ngOnInit() {

    this.subscriptions.add(this.activatedRoute.paramMap.subscribe(paramMap => {
      this.handleNavigation(paramMap);
    }));
}
Run Code Online (Sandbox Code Playgroud)

Val*_*kov 5

我也遇到过同样的问题,我想这是因为路由器不知道location.go()导航。因此,location.go()将位置 url 更改为http://localhost:4200/items;openedId=123但路由器当前 url 仍然是http://localhost:4200/items。当您按“后退”键时,路由器会忽略该事件,因为“后退”URL 与当前路由器 URL 匹配。如果您调用location.go()两次并导航回来,则该backurlhttp://localhost:4200/items;openedId=123与路由器 url 不匹配,因此paramMap会被触发。

解决方法可能是向网址添加一些唯一的参数,例如当前时间戳,我尝试过并且它有效,但这绝对不是最佳解决方案。我最终使用Route.navigate()而不是location.go(). 如果您想过滤某些导航,可以通过将状态传递给方法来过滤导航,然后您可以通过Router.getCurrentNavigation()navigate访问状态来过滤导航

问题是该位置不是为路线更改而设计的,服务文档告诉我们

最好使用 Router#navigate 服务来触发路由更改。仅当您需要在路由之外与 URL 交互或创建规范化 URL 时才使用 Location。