加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:37:09 所属栏目:安全 来源:网络整理
导读:我有一个Angular 5应用程序. 我的app组件中有以下代码. 我想隐藏特定路线的导航栏和顶部栏. 是否可以在app.component.ts中获取当前激活的路由?如果是的话,怎么样? 如果不可能,有没有解决方案来解决这个问题(使用警卫或其他什么……)? 还要记住,它应该是被
我有一个Angular 5应用程序.

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

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

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

如果不可能,有没有解决方案来解决这个问题(使用警卫或其他什么……)?

enter image description here

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

解决方法

试试这个:

在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读