Angular 2 路由器事件没有第一次触发? [英] Angular 2 router event not firing first time?

查看:27
本文介绍了Angular 2 路由器事件没有第一次触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个组件路由到另一个组件.路由完成后,我想使用上一个路由中的 URL.我已将下面的代码放入要路由到的组件的构造函数中,但它不会在第一条路由上触发.在第一条路线之后,该功能每次都会触发.

I am routing from one component to another. Once the route is done I would like to use the URL from the previous route. I have put the code below into the constuctor of the component being routed to, but it does not fire on the first route. After the first route, the function fires every time.

this.router.events
      .filter(e => e instanceof NavigationEnd)
      .pairwise().subscribe((e) => {
          console.log(e);
    });

如果我删除成对函数,它似乎会在第一条路线上触发,但它只列出当前路线,而不是上一条路线.

If I remove the pairwise function it seems to fire on first route, however it lists only the current route, not the previous route.

 router.events
  .filter(e => e instanceof NavigationEnd)
  .subscribe(e => {
    console.log(e);
 });

我的目标是在新组件路由到时检索以前的路由.我在这里做错了什么?

My goal is to retrieve the previous route when the new component is routed to. What am I doing wrong here?

推荐答案

正如我所见,所有这些解决方案都传递到 route.snapshot 并尝试将 NavigationEnd 操作与它结合起来.但是,如果您尝试访问该页面 - 它不会被 router.events 的第一个 NavigationEnd 触发.快照也会触发父路由,而不是子路由.所以首先你可以使用子路由,但它也不会被首先触发......

As I see all these solutions relay to route.snapshot and try to combine NavigationEnd action with it. But if you try to access the page - it is not fired with the first NavigationEnd by router.events. Also snapshot fires parent route, not a child route. so first you could use child route, but it will be also not fired as first...

this.router.events.pipe(
  filter((event) => event instanceof NavigationEnd),
  map(() => this.aRoute.snapshot),
  map((route) => {
    while (route.firstChild) {
      route = route.firstChild;
    }
    return route;
  })
)

所以对我来说最好的解决方案是在正确当前路线上第一次开火使用router.events + router.url和一种类型导航结束:

so BEST solution for me with first fire on proper current route is using router.events + router.url with one type NavigationEnd:

 this.router.events
   .pipe(
      filter((event) => event instanceof NavigationEnd),
      startWith(this.router)
   )
   .subscribe((event: NavigationEnd) => {
     // there will be first router.url - and next - router events
 })

这篇关于Angular 2 路由器事件没有第一次触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆