Ответ 1
Первый ребенок предоставит вам доступ к данным
constructor(route: ActivatedRoute) {
route.url.subscribe(() => {
console.log(route.snapshot.firstChild.data);
});
}
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
нет. У меня есть доступ к массиву всех детей, но я не знаю, какой из них активирован.
Как я могу получить доступ к данным активированного дочернего маршрута из родительского компонента маршрута?
Первый ребенок предоставит вам доступ к данным
constructor(route: ActivatedRoute) {
route.url.subscribe(() => {
console.log(route.snapshot.firstChild.data);
});
}
Работая с Angular 6, мне удалось получить данные текущего маршрута из родительского компонента со следующим кодом:
Я настроил маршрутизатор с дополнительными параметрами для наследования данных родительских маршрутов:
@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());
}
Наслаждайтесь!