Angular 2+:如何访问路由器插座外的活动路由 [英] Angular 2+: How to access active route outside router-outlet

查看:27
本文介绍了Angular 2+:如何访问路由器插座外的活动路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 5 应用程序.

I have an Angular 5 application.

我的应用组件中有以下代码.

I have the following code in my app component.

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

I want to hide navbar and topbar for particular routes.

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

Is it possible to get currently activated route in app.component.ts ? if so, How ?

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

If not possible, is there any solution to resolve this ( using guards or whatever else ... )?

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

Also keep in mind that it should be reactive. when i switch to another route sidebar and navbar should show again.

推荐答案

试试这个:

在 app.component.ts 中

in 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

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 },
])

您可以随意修改它.

现场演示

这篇关于Angular 2+:如何访问路由器插座外的活动路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆