代码之家  ›  专栏  ›  技术社区  ›  Chris Smith

设置浏览器反向角度导航的URL片段

  •  0
  • Chris Smith  · 技术社区  · 6 年前

    是否可以自定义角度路由器的背面行为?具体来说,我想添加一个基于浏览器资源的URL片段 从导航 .

    例如,如果浏览器打开 http://example.com/purchases/42 ,向后导航将使用户转到 http://example.com/purchases#42 而不是 http://example.com/purchases . 这是可取的,因为/purchases页面可能很长,URL片段可以将浏览器放置在前一页的上下文中。

    这样的事情有可能吗?只有通过使用 History API ,或者是否有其他一些API可以让角度用户管理导航状态?

    1 回复  |  直到 6 年前
        1
  •  1
  •   dAxx_    6 年前

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

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

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

    我们现在可以通过名为 视图端口滚动条 @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);
      }
    }
    

    这是一个如何使用它的例子,为了得到完整的解释,您应该访问 post

    推荐文章