Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Custom Route Data from lazy loaded route in top level component

I am using Angular 5 and I seem to not be able to get data from ActivatedRoute using methods stated in other answers to my question.

app.routes.ts

export const AppRoutes = [
    {
        path : '',
        component: HomeView,
        pathMatch: 'full', data: {key: 'home', label: 'Home'}},
    {
        path : 'about',
        loadChildren: './+about/about.module#AboutModule'
    },
    {
        path : 'account/:id',
        loadChildren: './+account/account.module#AccountModule',
        canActivate: [AuthGuard],
        data: {key: 'account', label: 'My Account'}
    },
];

app.component.ts

@Component({
    selector: 'ou-app',
    templateUrl: 'app.component.html',
    styleUrls: ['../styles/main.scss'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
    constructor(
        private router: Router,
        private route: ActivatedRoute,
    ){}

    ngOnInit(){
        this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
            console.log('router events console... ', this.route);
        });
    }
}

I can't seem to get the data from the route under snapshot, root, children, firstChild, everything is null, or undefined

like image 749
Lukas Sorensen Avatar asked Dec 07 '22 15:12

Lukas Sorensen


1 Answers

The issue is that you are not at the route that you are trying to look at. You need to go through the child routes. There is an example here: Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute

I was able to modify your code as follows using the info from the above link.

  router.events
    .filter(event => event instanceof NavigationEnd)
    .map(() => this.activatedRoute)
    .map(route  => {
      console.log(route.snapshot.data);
      while (route .firstChild) route = route.firstChild;
      return route;
    })
    .mergeMap(route => route.data)
    .subscribe(x => {
      console.log('router events console... ', x);
    });

With this code I was able to get this:

enter image description here

Update: With RxJs v5.5 and above

ngOnInit() {
    this.router.events
        .pipe(
            filter((event) => event instanceof NavigationEnd),
            map(() => this.activatedRoute),
            map((route) => {
                while (route.firstChild) {
                    route = route.firstChild;
                }
                return route;
            }),
            mergeMap((route) => route.data))
        .subscribe((event) => console.log('router events console... ', event));
}
like image 72
DeborahK Avatar answered May 15 '23 07:05

DeborahK