如何从父路由的组件访问激活的子路由数据?

时间:2017-05-05 13:25:59

标签: angular angular2-routing

const appRoutes: Routes = [
  { path: 'parent', component: parentComp, data: { foo: 'parent data' }, children: [
    { path: 'child1', component: childComp1, data: { bar: 'child data 1' },
    { path: 'child2', component: childComp2, data: { bar: 'child data 2' }
  ]}
];

如果我导航到/parent/child2,然后查看ActivatedRoute中的parentComp,则会定义data.foo,但data.bar不会。我可以访问所有孩子的数组,但我不知道哪一个被激活。

如何从父路径的组件访问激活的子路由数据?

5 个答案:

答案 0 :(得分:19)

第一个孩子将授予您访问数据的权利

constructor(route: ActivatedRoute) {
  route.url.subscribe(() => {
    console.log(route.snapshot.firstChild.data);
   });
}

答案 1 :(得分:9)

使用Angular 6,我设法从父组件获取当前路由数据,并使用以下代码:

我已使用Extra选项配置路由器以继承父路由数据:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      initialNavigation: 'enabled',
      paramsInheritanceStrategy: 'always'
    }),
  ...
})
export class AppModule {}

然后在我的父组件中,我能够看到数据更改:

import { ActivatedRoute, ActivatedRouteSnapshot, NavigationEnd, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';

subs: Array<Subscription> = [];

constructor(private router: Router, private route: ActivatedRoute) {
  this.subs[0] = this.router.events
    .pipe(
      filter(event => event instanceof NavigationEnd),
      map(() => this.route.snapshot),
      map(route => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;
      })
    )
    .subscribe((route: ActivatedRouteSnapshot) => {
      console.log(route.data);
    });
}

ngOnDestroy() {
  this.subs.forEach(s => s.unsubscribe());
}

享受!

答案 2 :(得分:3)

在Angular 8中使用:

data: any;

constructor(route: ActivatedRoute) {
  this.data = route.snapshot.firstChild.data;
}

答案 3 :(得分:3)

我正在使用Angular 8

这是路线

      {
    path: '',
    component: DefaultLayoutComponent,
    canActivate: [AuthGuardService],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent,
        data: { title: 'Summary' },
      },
      {
        path: 'account',
        component: AccountComponent,
        data: { title: 'account' },

      },
      {
        path: 'setup',
        component: setupComponent,
        data: { title: 'setup' },

      },
      {
        path: 'help',
        component: helpComponent,
        data: { title: 'help' },

      },
    ],
  }

父组件-DefaultLayoutComponent


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

ngOnInit(): void {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        const title = this.route.snapshot.firstChild.data;
        console.log('title-', title);

      }
    });
}

控制台输出 Access to the data in my parent component

答案 4 :(得分:0)

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';

@Component({
  selector: 'sources',
  templateUrl: './sources.component.html',
  styleUrls: ['./sources.component.scss'],
})
export class SourcesComponent implements OnInit, OnDestroy {

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

  private sub: Subscription;
  public title: string;

  ngOnInit() {
    this.sub = this.router.events.pipe(
      filter(event=> event instanceof NavigationEnd)
    )
    .subscribe(events=>{
      console.log(this.route.snapshot.firstChild.data);
    })
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

}

我的路由器看起来像:

const routes: Routes = [
  {
    path: '',
    component: SourcesComponent,
    children: [
      {
        path: 'source',
        component: SourcesTableComponent,
        data: {title : 'Источники'},
      },
      {
        path: 'category',
        component: CategoryComponent,
        data: {title : 'Категории'}
      },
      {
        path: 'relation',
        component: RelationComponent,
        data: {title : 'Сведение категорий'}
      },
    ]
  },
];