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

前端 未结 5 2005
走了就别回头了
走了就别回头了 2021-01-26 09:17

I\'ve been trying to find a simple solution.

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 wa

相关标签:
5条回答
  • 2021-01-26 09:30

    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

    0 讨论(0)
  • 2021-01-26 09:37

    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"

    0 讨论(0)
  • 2021-01-26 09:39

    you don't want to pay an object through a router. Instead pass an id and then re-look up the item on the new page. That way if you refresh the new page, everything still works.

    0 讨论(0)
  • 2021-01-26 09:43

    Please try like this

    <ul>
        <li *ngFor="let product of products">
            <a [routerLink]="['/product/',product.id]"></a>
        </li>
    </ul>
    
    0 讨论(0)
  • 2021-01-26 09:51

    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.

    0 讨论(0)
提交回复
热议问题