Angular 组合多个路由器事件

问题描述 投票:0回答:1

我只是有一个查询,我有两个路由器事件片段

    this.router.events.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
      .subscribe((events: RoutesRecognized[]) => {
        this.previousUrl = events[0].urlAfterRedirects;
        this.currentUrl = events[1].urlAfterRedirects;
});

this.router.events
.pipe(filter(e => e instanceof NavigationStart))
.subscribe((e: NavigationStart) => {
  const navigation = this.router.getCurrentNavigation();
});

虽然这些单独工作正常,

为了优化,我可以合并/组合此路由器事件并仅使用一个吗?。

angular rxjs rxjs6
1个回答
1
投票

我们当然可以。为什么我们需要监听同一个事件发射器两次? 你可以做这样的事情:

    this.router.events.pipe(pairwise())
  .subscribe((events: any) => {
    if (events[0] instanceof NavigationStart) {
      const navigation = this.router.getCurrentNavigation();
    } else if (events[1] instanceof RoutesRecognized) {
      this.previousUrl = events[0].urlAfterRedirects;
      this.currentUrl = events[1].urlAfterRedirects;
    }
  });

您无需在顶部过滤事件,而是监听所有内容并根据事件类型应用逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.