Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

angular - 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. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First child will give you access to data

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...