我有一个Angular 5应用程序.
我的app组件中有以下代码.
我想隐藏特定路线的导航栏和顶部栏.
是否可以在app.component.ts中获取当前激活的路由?如果是的话,怎么样?
如果不可能,有没有解决方案来解决这个问题(使用警卫或其他什么……)?
还要记住,它应该是被动的.当我切换到另一个路线边栏时,导航栏应该再次显示.
解决方法
试试这个:
在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 },])
您可以随意修改它.