如何获得角度2的当前路线自定义数据?

问题描述 投票:18回答:9

我设置的路线如下

const appRoutes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    data: {
      title: 'Login TTX'
    }
  },
  {
    path: 'list',
    component: ListingComponent,
    data: {
      title: ' TTX Home Page',
      module:'list'
    }
  },
  {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
];

现在,当我来到'/list'路线然后在'listing.component.ts'我写了下面的代码

export class ListingComponent {

  public constructor(private router:Router) {
      //here how i can get **data** of **list** routes

  }
}
angular angular2-routing
9个回答
16
投票
  public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['title']);
  }

21
投票

对于Angular 4+

如果将以下代码放在父级或上级组件(如AppComponent)中,则它将不起作用。它仅适用于您已为其定义路径自定义数据的子级或低级组件:

 public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['title']);
  }

因此,如果您想从父级或上级组件全局访问路由自定义数据以访问路由自定义数据中的更改,那么您将收听路由器事件,尤其是RoutesRecognizedNavigationEnd事件。我要用AppComponent和两个事件展示两个程序:

第一种方法:

   export class AppComponent implements OnInit, AfterViewInit {

    constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

    ngOnInit() {
         this.router
        .events
        .filter(event => event instanceof NavigationEnd)
        .map(() => {
          let child = this.activatedRoute.firstChild;
          while (child) {
            if (child.firstChild) {
              child = child.firstChild;
            } else if (child.snapshot.data && child.snapshot.data['custom_data']) {
              return child.snapshot.data['custom_data'];
            } else {
              return null;
            }
          }
          return null;
        }).subscribe( (customData: any) => {
          console.log(customData);
       });
    }
 }

第二种方法是使用:

this.router.events
.filter(event => event instanceof RoutesRecognized)
.map( (event: RoutesRecognized) => {
    return event.state.root.firstChild.data['custom_data'];
})
.subscribe(customData => {
    console.log(customData);
});

注意:尽管最后一个较短且通常有效,但是,如果您有嵌套路线,则鼓励使用第一个。


6
投票

它为无法导航的组件工作(如标题):

this.route.root.firstChild.snapshot.data['title']

完整的例子:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';


export class HeaderComponent implements OnInit {
  title: string;

  constructor(private route: ActivatedRoute, private router: Router ) { }

  ngOnInit() {
    this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd) {
        this.title = this.route.root.firstChild.snapshot.data['title']
      }
    });
  }    
}

归功于这个qazxsw poi


6
投票

在我测试了各种解决方案后,角度支持小组的答案实际上很好地解决了这个问题。

answare,这是检测ActivatedRoute doesn't carry data中页面变量的解决方案。

data: { page: 'login' }

5
投票

asmmahmud的答案适用于Angular 5.x但6.X打破了import { Router, RoutesRecognized } from '@angular/router'; export class AppComponent { page = ''; constructor(private router: Router) { // listen to page variable from router events router.events.subscribe(event => { if (event instanceof RoutesRecognized) { let route = event.state.root.firstChild; this.page = 'page-' + route.data.page || ''; console.log('Page', this.page); } }); } } ,因为rxjs 6.x有突破性变化。所以刚刚发现了一个更新:

this.router.events

1
投票

对于那些现在使用Angular 6+和最新RXJS 6的人来说,这是基于以上的ansers:

路由示例:

import {filter} from 'rxjs/operators';
import {map, mergeMap} from 'rxjs/internal/operators';

router.events
          .pipe(filter(event => event instanceof NavigationEnd),
            map(() => {
              let route = activatedRoute.firstChild;
              let child = route;
              while (child) {
                if (child.firstChild) {
                  child = child.firstChild;
                  route = child;
                } else {
                  child = null;
                }
              }
              return route;
            }),
            mergeMap(route => route.data)
          )
          .subscribe(data => {
            console.log(data);
          });

如何获得标题示例:

const routes: Routes = [
  {path: 'home', component: HomeComponent, data: {title: 'Home'}},
  // {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'login', component: LoginComponent, data: {title: 'Login'}},
  {path: 'dashboard', component: DashboardComponent, data: {title: 'Dashboard'}, canActivate: [AppAuthGuard]},
  {path: 'eventDetails', component: EventCardComponent, data: {title: 'Details'}},
  {path: '**', redirectTo: 'home', pathMatch: 'full'},
];

0
投票

这在app.component.ts(ng 5)中适用于我

ngOnInit() {
    this.routerEventSubscription = this.router.events
      .pipe(filter(event => event instanceof RoutesRecognized))
      .pipe(map((event: RoutesRecognized) => {
        return event.state.root.firstChild.data['title'];
      })).subscribe(title => {
        this.title = title;
      });
  }

0
投票

如果你想拥有当前的路线数据,可以从 constructor( private router: Router, ) { router.events.subscribe((routerEvent: Event) => { this.checkRouterEvent(routerEvent); }); } checkRouterEvent(routerEvent: Event): void { if (routerEvent instanceof ActivationStart) { if (routerEvent.snapshot.data.custom_data) { this.currentpage = routerEvent.snapshot.data['custom_data']; console.log('4.' + this.currentpage); } } 获得

ActivatedRoute

0
投票

您可以订阅ActivatedRoute.data。这在某种程度上与@ dinesh-kumar的答案类似,但我相信public constructor(private activatedRoute:ActivatedRoute) { console.log((activatedRoute.data as any).value); } 充分利用了这个事实,即(activatedRoute.data as any).value被实现为BehaviorSubject。但activatedRoute.data暴露为ActivatedRoute.data,所以正确的方式是订阅(不要忘记取消订阅,或Observable<Data>等)或使用take(1)管等。

async
© www.soinside.com 2019 - 2024. All rights reserved.