Angular 2+:如何访问router-outlet外的active route

Angular 2+: How to access active route outside router-outlet

我有一个 Angular 5 申请。

我的应用程序组件中有以下代码。

我想隐藏特定路线的导航栏和顶部栏。

是否可以在app.component.ts中获取当前激活的路线?如果是这样,如何?

如果不可能,是否有任何解决方案来解决这个问题(使用警卫或其他...)?

另请记住,它应该是反应式的。当我切换到另一条路线时,侧边栏和导航栏应该再次显示。

当然可以。你可以过滤路由器事件,只获取激活的路由,然后,你可以在里面找到每条路由的一些信息(抱歉,现在不能说,但我记得,你应该只获取 "activated right now" 路由,这看起来像您要搜索的内容):

constructor(private _router: Router) {
  _router.events
    .filter(event => event instanceof NavigationEnd) 
    .forEach(item => {
      console.log(item);
      console.log(_router.routerState.root);
      console.log(_router.routerState.root.firstChild);
    });
}

您可以简单地使用 ngIf

在你的组件ts文件中

import { Router } from '@angular/router'

constructor(private router: Router)

在你的html

<app-navbar *ngIf="!(router.url === '/example')">
</app-navbar>

试试这个:

在 app.component.ts

import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
  showSidebar$: Observable<boolean>;
  private defaultShowSidebar = true;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
  ) {
    this.showSidebar$ = this.router.events.pipe(
      filter(e => e instanceof NavigationEnd),
      map(() => activatedRoute),
      map(route => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;
      }),
      mergeMap(route => route.data),
      map(data => data.hasOwnProperty('showSidebar') ? data.showSidebar : this.defaultShowSidebar),
    )
  }

app.component.html

<aside *ngIf="showSidebar$ | async">Sidebar here</aside>

<router-outlet></router-outlet>

<a routerLink="/without-sidebar">Without sidebar</a>
<a routerLink="/with-sidebar">With sidebar</a>
<a routerLink="/without-data">Without data.showSidebar</a>

应用程序路由

RouterModule.forRoot([
  { path: 'with-sidebar', component: WithSidebarComponent, data: { showSidebar: true } },
  { path: 'without-sidebar', component: WithoutSidebarComponent, data: { showSidebar: false } },
  { path: 'without-data', component: WithoutDataComponent },
])

您可以随意修改。

Live demo

要在不订阅路由器事件的情况下获取活动路由,您可以简单地使用 while 循环递归地找到最低的 child。

private getActivatedRoute(): ActivatedRoute {
    let route = this.router.routerState.root;
    while (route.firstChild) {
        route = route.firstChild;
    }
    return route;
}