Angular 2+:如何访问路由器插座外的活动路由

时间:2018-04-03 14:05:26

标签: angular angular-router

我有一个Angular 5应用程序。

我的app组件中有以下代码。

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

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

如果不可能,有没有解决方案(使用警卫或其他任何......)?

enter image description here

还要记住它应该是被动的。当我切换到另一个路线边栏时,导航栏应该再次显示。

4 个答案:

答案 0 :(得分:6)

试试这个:

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>

app路线

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

答案 1 :(得分:1)

不确定。你可以过滤路由器事件并只获取激活的路线,然后,你可以找到一些关于里面每条路线的信息(对不起,现在还不能说,但是我记得,你应该只获得“现在激活”路线,看起来像你正在寻找的东西):

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);
    });
}

答案 2 :(得分:1)

要获得活动路由而不订阅路由器事件,您可以简单地递归使用while循环来找到最低的子级。

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

答案 3 :(得分:-2)

您只需使用ngIf

即可

在你的组件ts文件

import { Router } from '@angular/router'

constructor(private router: Router)

在你的HTML中

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