I am using Angular Router and have the following nested route(s):
{
path: 'resource/:id',
component: ResourceComponent,
children: [
{
path: 'general',
component: ResourceGeneralComponent
},
{
path: 'background',
component: ResourceBackgroundComponent
}
]
}
ResourceComponent
fetches a resource from a REST-API and contains a <router-outlet>
in which the other components are rendered. The child route components should display different sections of the fetched data. I can get my data into the child components when i click on the corresponding link, using history.state
. This however does not work when navigating to url/resource/1/general
, because ResourceGeneralComponent
does not have the required data from ResourceComponent
.
I am passing the resource in the state through the link like this. Like i said clicking the link works fine.
<a routerLink="general" [state]="{resource: resource}" routerLinkActive="active" class="nav-link">General</a>
How do i get the resource into the child components so that it works without using history.state
? I tried subscribing to an observable in the service that both the parent and child components share but the function passed to subscribe in child does not get called (probably because parent fires the observable event before child is rendered).
How do i pass data to the child components correctly?
Use ReplaySubject, this will replay any number of old values to new subscribers when they first subscribe.
Using a ReplaySubject
with a bufferSize
of 1
will replay the last/current value to new subscribers. That should be sufficient in your case.