I'm using Angular 7, and I'm trying to get data from my routes.
I have my lazy loaded routes set up like so:
{
data: { menuItems: DASHBOARD_MENU_ITEMS },
path: 'dashboard',
loadChildren: './modules/dashboard/dashboard.module#DashboardModule',
},
{
data: { menuItems: ADMIN_MENU_ITEMS },
path: 'admin',
loadChildren: './modules/admin/admin.module#AdminModule'
}
And I have an observable to get that data like so:
menuItems$: Observable<any[]>;
In one of my components, I have the following:
this.menuItems$ = this.route.firstChild.firstChild.data;
this.menuItems$ = this.router.events.pipe(
// startWith(this.route.firstChild.firstChild.data),
filter(e => e instanceof RoutesRecognized),
map((event: RoutesRecognized) => {
console.log(event.state.root.firstChild.firstChild.firstChild.data)
return event.state.root.firstChild.firstChild.firstChild.data as NbMenuItem[];
}));
But this isn't working for me, as I believe I am reassigning my observable variable menuItems$
.
I need to do this as I need to get the data both the first time a route is hit (which does not trigger an event from this.router.events
), and every time the user navigates.
If I use the .subscribe()
notation, then it works fine, but I don't want to do that. What am I doing wrong here?
I believe you're passing an Observable into startWith
rather than passing the initial state. You can grab the initial state using the snapshot
property.
You'll also need to place the startWith
operator after the filter
and map
.
const initialMenuItems = this.route.firstChild.firstChild.snapshot.data;
this.menuItems$ = this.router.events.pipe(
filter(e => e instanceof RoutesRecognized),
map((event: RoutesRecognized) => {
console.log(event.state.root.firstChild.firstChild.firstChild.data);
return event.state.root.firstChild.firstChild.firstChild.data as NbMenuItem[];
}),
startWith(this.route.firstChild.firstChild.data)
);