在浏览器上设置 URL 片段 Angular 中的后退导航

Set URL fragment on browser Back navigation in Angular

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

例如,如果浏览器打开 http://example.com/purchases/42, navigating back would take the user to http://example.com/purchases#42 instead of http://example.com/purchases。这是可取的,因为 /purchases 页面可能很长,并且 URL 片段可以将浏览器定位在上一页的上下文中。

这种事情有可能吗?完成此操作的唯一方法是使用 History API,还是 Angular 用户使用其他一些 API 来管理导航状态?

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

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

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

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

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);
  }
}

这是您现在可以如何使用它的示例,如需完整说明,您应该访问 post