简体   繁体   English

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

[英]How can I access an activated child route's data from the parent route's component?

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' }
  ]}
];

If I navigate to /parent/child2 and then look at the ActivatedRoute from parentComp , data.foo is defined, but data.bar is not.如果我导航到/parent/child2 child2 然后查看来自parentCompActivatedRoute ,则定义了data.foo ,但没有定义data.bar I have access to an array of all the children, but I don't know which one is activated.我可以访问所有子项的数组,但我不知道激活了哪个。

How can I access the activated child route's data from a parent route's component?如何从父路由的组件访问激活的子路由的数据?

First child will give you access to data第一个孩子会让你访问数据

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

Working with Angular 6, I managed to get the current route data from a parent component, with the following code:使用 Angular 6,我设法从父组件获取当前路由数据,代码如下:

I've configured the Router with the Extra options to inherit the parent routes data:我已经使用额外选项配置了路由器来继承父路由数据:

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

Then in my parent component, I was able to see the data changes with:然后在我的父组件中,我能够看到数据的变化:

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());
}

Enjoy!享受!

In Angular 8 work with:在 Angular 8 中使用:

data: any;

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

I am using Angular 8我正在使用 Angular 8

Here is the routes以下是路线

      {
    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' },

      },
    ],
  }

Parent Component - DefaultLayoutComponent父组件 - 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);

      }
    });
}

Output from console Access to the data in my parent component控制台输出访问我的父组件中的数据

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();
  }

}

My router looks like:我的路由器看起来像:

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 : 'Сведение категорий'}
      },
    ]
  },
];

Still spend some time to get a correct answer.还是要花一些时间才能得到正确答案。 ActivationEnd event what helped me ActivationEnd事件对我有什么帮助

Router example:路由器示例:

const routes: Routes = [
{
    path: '',
    component: CustomComponent, // HTML parent wrapper with menu 
    data: {},
    children: [
        {
            path: '',
            component: SearchComponent,
            data: { someId: 'id-1' }
        },
        {
            path: 'somePath/create',
            pathMatch: 'full',
            component: CreateComponent,
            data: { someId: 'id-2' }
        },

Under your parent CustomComponent在您的父级 CustomComponent 下

    constructor( private router: Router ) {

       this.router.events
        .pipe(filter((routerEvent) => routerEvent instanceof ActivationEnd))
        .subscribe((routerEvent: ActivationEnd | any) => {
            const data = routerEvent.snapshot.data;
            if (data?.someId) {
                console.log('someId', data.someId);
            }
        });
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从父组件访问作为子路由的组件? - How can I get access to a component that is a child route from the parent component? 如何从 Angular 中的子路由组件访问父组件属性? - How to access parent component properties from a child route component in Angular? 如何从子组件中访问映射到父组件的路由参数? (角度 2.0) - How do I access route parameters that are mapped to a parent component from within a child component? (angular 2.0) 访问来自其他组件的激活路径数据 - Access activated route data from some other component 如何从导航触发的路由解析器访问先前激活的组件? - How to access previous activated component from a route resolver triggered by a navigation? 当我使用路由器插座时,如何从父级制作子级路由中的空组件 - How can i make empty component in the child route,from the parent,when i use router outlet 如何使用activatedRoute从子组件获取父路由参数? - How can I get a parent route params from a child component using activatedRoute? 如何访问或检查超级父级组件中子组件的模板驱动表单的验证 - How can I access or check validation of the child component's template driven form in the super parent's component 如何根据已解析的路由数据路由到子路由? - How can I route to a child route based on the resolved route data? 子路线在其下方显示父级的html组件 - Child route shows parent's html component below it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM