首页 > 解决方案 > 在浏览器上设置 URL 片段 在 Angular 中返回导航

问题描述

是否可以自定义 Angular 路由器的后退行为?具体来说,我想根据浏览器从中导航的资源添加一个 URL 片段。

例如,如果浏览器在http://example.com/purchases/42上,则向后导航会将用户带到http://example.com/purchases#42而不是http://example.com/purchases。这是可取的,因为 /purchases 页面可能很长,并且 URL 片段可以将浏览器定位在前一页面的上下文中。

这样的事情甚至可能吗?实现这一点的唯一方法是使用History API,还是 Angular 用户可以使用其他 API 来管理导航状态?

标签: angular6angular-router

解决方案


好吧,幸运的是,在新的 Angular 6.1 中,您可以启用路由器的一项新功能,当您回击时,您的路由器将“记住”您的最后滚动位置。
您必须像这样设置路由器模块:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'
  })

现在的问题是它是一个非常新的功能,它只适用于静态页面。这意味着如果您从服务或其他东西中获取内容,恢复将在您实际拥有数据之前尝试自行设置,因此位置将失败。(目前,即使您使用解析器,它也会失败)

我们现在可以通过名为viewportScroller的新服务使用一种解决方法@angular/router package,但您必须手动操作。(目前,它可能会在不久的将来得到修复)。

export class PendingRacesComponent {
  scrollPosition: [number, number];
  races: Array<RaceModel>;

  constructor(route: ActivatedRoute, private router: Router, private viewportScroller: ViewportScroller) {
    this.races = route.snapshot.data['races'];
    this.router.events.pipe(
      filter(e => e instanceof Scroll)
    ).subscribe(e => {
      if ((e as Scroll).position) {
        this.scrollPosition = (e as Scroll).position;
      } else {
        this.scrollPosition = [0, 0];
      }
    });
  }
  ngAfterViewInit() {
    this.viewportScroller.scrollToPosition(this.scrollPosition);
  }
}

这是您现在如何使用它的示例,有关完整说明,您应该访问该帖子


推荐阅读