问题
I have a route config
@RouteConfig([
{ path: '/', name: 'Start', component: Journal },
{ path: '/register', name: 'Register', component: Register },
{ path: '/login', name: 'Login', component: Login },
{ path: '/settings', name: 'Settings', component: Settings },
])
I'd like to listen to events emitted from Journal's @Output. How can I do that when the only reference I have in the template is
<a class="nav-item nav-link" [routerLink]="['Journal']">Journal</a>
?
回答1:
I realize this is pretty old now, but passing state to the route is undoable. This is mostly because routerLink is generic and could take any number of potential children. So even if you could pass state or process its events, you would end up with unneeded complexity.
The correct way to manage state between parent and child components, is a shared service. Essentially, it comes down to these steps:
- Write a service.
- Provide the service not from your module, but from the parent component (to make it inaccessible to outside code).
- Inject the service into the parent and any children that would need it.
This would work equally well with state passed into the child and with notifications received from the child and doesn't pollute the route setup.
来源:https://stackoverflow.com/questions/35878762/how-do-you-attach-an-eventemitter-output-to-a-component-under-routing