问题
I've been trying to find a simple solution, but it appears its not possible. It's a very simple concept that pretty much every angular programmer encounters, but there appears to be no easy solution, which surprises me.
I have a for loop displaying a list of items. clicking on one of the items routes you to the detailed component and I just want the selected item to be available in the detailed component. For some reason there is no simple solution (that I am aware of). I would expect there to be something like this:
<div *ngFor="let item of items" [routerLink]="['/item-details']" [selectedItem]=item>
that's what I want. but, of course it doesn't work.
so instead I am passing the item id as a queryParams element, and then doing a Service call on the detail component to retrieve the item. It works fine but seems like a lot of work to do something that should be so simple.
am I missing something?
回答1:
Objects passing by routing is limited options. Using a service is the better option. If you provide a service instance by the parent component, then the same instance gets injected in parent and child and you have the shared data available immediately.
https://stackblitz.com/edit/angular-6-communicating-between-components-1gunkw?file=app%2Fapp.component.ts
回答2:
Please try like this
<ul>
<li *ngFor="let product of products">
<a [routerLink]="['/product/',product.id]"></a>
</li>
</ul>
回答3:
What i think about why there is no way to pass an object through a router is because if you pass the data and made it available on the route2
,
the data is available on the route2
just because it is passed from route1
.
What happens if you refresh route2
??
from where will you get the data for route2
, your page would collapse.
回答4:
From Angular 7.2 you can pass argument to router, see this great link
In .html you must use [state], e.g.
<div *ngFor="let item of items" [routerLink]="['/item-details']" [state]=item>
Two get the state you has two options, from a component not main-app, see this answer, from the main-app you can subscribe to router.events
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
).subscribe((res:any)=>{
console.log(res)
})
NOTE: if use this aproach, remember that if you access directly to your "item-details.component", you has any "item"
来源:https://stackoverflow.com/questions/58886303/angular-no-way-to-pass-an-object-through-a-router