Angular 2如何使用路由器和location.go()检测后退按钮按下?

2022-01-21 00:00:00 javascript angular angular-ui-router

我已经构建了一个使用 router 3.0.0-beta.1 在应用程序部分之间切换的应用程序.我还使用 location.go() 来模拟同一页面的子部分之间的切换.我使用了 <base href="/"> 和一些 URL 重写规则,以便在页面刷新时将所有路由重定向到 index.html.这允许路由器接收请求的小节作为 URL 参数.基本上我已经设法避免使用 HashLocationStrategy.

I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href="/"> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.

routes.ts

export const routes: RouterConfig = [
    {
        path: '',
        redirectTo: '/catalog',
        pathMatch: 'full'
    },
    {
        path: 'catalog',
        component: CatalogComponent
    },
    {
        path: 'catalog/:topCategory',
        component: CatalogComponent
    },
    {
        path: 'summary',
        component: SummaryComponent
    }
];

如果我点击导航栏中的一个小节,会发生 2 件事:

If I click on a subsection in the navigation bar 2 things happen:

  • logation.go() 使用必要的字符串更新 URL 以指示当前小节
  • 自定义 scrollTo() 动画在请求的小节顶部滚动页面.
  • logation.go() updates the URL with the necessary string in order to indicate the current subsection
  • A custom scrollTo() animation scrolls the page at the top of the requested subsection.

如果我刷新页面,我将使用先前定义的路线并提取必要的参数以恢复滚动到请求的小节.

If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.

this._activatedRoute.params
    .map(params => params['topCategory'])
    .subscribe(topCategory => {
        if (typeof topCategory !== 'undefined' &&
            topCategory !== null
        ) {
            self.UiState.startArrowWasDismised = true;
            self.UiState.selectedTopCategory = topCategory;
        }
    });

除了单击后退按钮外,一切正常.如果上一页是不同的部分,则应用路由器的行为与预期相同.但是,如果上一个页面/url 是一个小节,则 url 将更改为上一个,但 UI 中没有任何反应.如何检测是否按下后退按钮以调用 scrollTo() 函数再次完成它的工作?

All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it's job again?

我看到的大多数答案都依赖于事件 onhashchange,但这个事件不会在我的应用程序中被触发,因为毕竟我的 URL 中没有哈希...

Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall...

推荐答案

我不知道其他答案是否过时,但它们在 Angular 7 中对我来说都不是很好.我所做的是添加一个 Angular 事件侦听器通过将其导入我的组件:

I don't know if the other answers are dated, but neither of them worked well for me in Angular 7. What I did was add an Angular event listener by importing it into my component:

import { HostListener } from '@angular/core';

然后在 window 对象上监听 popstate(按照 Adrian 的建议):

and then listening for popstate on the window object (as Adrian recommended):

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    console.log('Back button pressed');
  }

这对我有用.

相关文章