Angular: 无法通过路由器传递对象?

Angular: no way to pass an object through a router?

我一直在努力寻找一个简单的解决方案。

我有一个显示项目列表的 for 循环。单击其中一项会将您带到详细组件,我只希望所选项目在详细组件中可用。出于某种原因,没有简单的解决方案(我知道)。我希望会有这样的事情:

``

``

这就是我想要的。但是,这当然行不通。

所以我将项目 ID 作为 queryParams 元素传递,然后对详细信息组件执行服务调用以检索项目。它工作正常,但似乎需要做很多工作才能完成本应如此简单的事情。

我是不是漏了什么?

请这样尝试

<ul>
    <li *ngFor="let product of products">
        <a [routerLink]="['/product/',product.id]"></a>
    </li>
</ul>

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

我认为为什么无法通过路由器传递对象是因为如果您传递数据并使其在 route2

上可用

数据在 route2 上可用只是因为它是从 route1 传递的。

如果刷新 route2 会发生什么??

您将从哪里获取 route2 的数据,您的页面会崩溃。

从 Angular 7.2 开始,您可以将参数传递给路由器,参见 this great link

在.html中你必须使用[state],例如

<div *ngFor="let item of items" [routerLink]="['/item-details']" [state]=item>

两个获取状态你有两个选项,来自一个组件而不是主应用程序,请参阅 ,您可以从主应用程序订阅 router.events

this.router.events.pipe(
  filter(e => e instanceof NavigationStart),
  map(() => this.router.getCurrentNavigation().extras.state)
).subscribe((res:any)=>{
   console.log(res)
})

注意:如果使用此方法,请记住如果您直接访问您的 "item-details.component",您有任何 "item"

您不想通过路由器支付物品。而是传递一个 id,然后 re-look 在新页面上将项目向上。这样,如果您刷新新页面,一切仍然有效。