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

After a Location.go(), History.back() does not trigger ActivatedRoute.paramMap

考虑这个 URL:

http://localhost:4200/items

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

http://localhost:4200/items;openedId=123

当我点击后退按钮时,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 (!)

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

更新:这是我监听 paramMap 变化的方式:

  public ngOnInit() {

    this.subscriptions.add(this.activatedRoute.paramMap.subscribe(paramMap => {
      this.handleNavigation(paramMap);
    }));
}

我不推荐使用 Location.go() 函数。

我能提出的最佳建议是在 GUI 中的元素上添加单击事件。点击事件会调用一个函数。

<div (click)="focusLocation('<INSERT LOCATION ID HERE>')">YOUR CONTENT</div>

focusLocation(queryParam) {
  this.router.navigate(['/items'], { queryParams: { openedId: queryParam } });
}

这应该始终激活 activatedRoute.params.subscribe(() => {});

干杯

我遇到了同样的问题,我猜这是因为 Router 不知道 location.go() 导航。因此,location.go() 将位置 url 更改为 http://localhost:4200/items;openedId=123,但路由器电流 url 仍为 http://localhost:4200/items。当您按下返回键时,路由器会忽略该事件,因为 'back' url 匹配当前路由器 url。如果您调用 location.go() 两次并返回,则 back url 是 http://localhost:4200/items;openedId=123 并且与路由器 url 不匹配,因此 paramMap 是触发。

一种解决方法可能是向 url 添加一些独特的参数,例如当前时间戳,我尝试过并且有效,但这绝对不是最佳解决方案。我最终使用了 Route.navigate() instead of location.go(). If you want to filter some navigations, it's possible by passing state to the navigate method, afterwards you can filter navigations by accessing the state via Router.getCurrentNavigation().

问题是 Location 不是为路线变化而设计的,服务 documentation tells:

It's better to use the Router#navigate service to trigger route changes. Use Location only if you need to interact with or create normalized URLs outside of routing.