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

时间:2018-08-06 17:48:37

标签: angular6 angular-router

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

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

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

1 个答案:

答案 0 :(得分:1)

幸运的是,在新的Angular 6.1中,您可以启用路由器的一项新功能,并且当您回击时,路由器会“记住”您的上一个滚动位置。
您必须这样设置路由器模块:

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