In Angular, I can define a route with data like so:
{
path: '/user/:id',
component: UserComponent,
data: {cache: {use: true, class: MyCacheClass}}
}
I would then be able to inject ActivatedRoute in my component and access the route data.
I can also link to the component in a template with the routerLink directive by using a link parameters array like so:
<a [routerLink]="['/user', id]">Profile</a>
If I wanted to pass the route data via a template routerLink I'm not sure how. The route data is not part of the route, so I couldn't do:
<a [routerLink]="['/user', id,
{cache: {use: true, class: MyCacheClass}}]">
Profile</a>
If I do this, Angular will try to navigate to:
/user/123;cache=[Object]
Can route data be passed via the routerLink directive and its link parameters array so that I can fetch it from the ActivatedRoute?
PS: To be clear, I am not asking for how I can encode the object within the url itself; I'm asking how to pass it to routerLink so that I can get it by injecting ActivatedRoute or ActivatedRouteSnapshot and fetching their data property
You can't. It's against Angular Router design.
Folks deal with such pattern with state management libs such as NGRX/NGXS/Akita or self-designed services.
If your objects are persistent, I'd recommend creating some hash map, and encoding the key in the URL. That way when you navigate from bookmarks etc, exact state could be restored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With