Search code examples
angularangular-routerangular-resolver

How to push data between routes in Angular


Assume I am given an item-list array in route /items/. The item-list.component.html looks something like this:

<div *ngFor="let item of items">
    ....
  <a [routerLink]="'/items/' + item.id">View Item</a>
</div>

What I'm trying to do is push the item object from the item-list array to the next page (or route) /items/:item-id.

Currently, the way I have it set up is with 2 resolvers, one for each route:
1. GET items-list
2. GET item by id

I realize that there is an unnecessary API call between these routes as the item object I need is already in the array. I plan to refactor the resolver call the API if the item doesn't exist (due to page refresh or direct link)

How would I approach this?

Note: In Ionic3 this could be done like this: navCtrl.push('ItemPage', {item: item});


Solution

  • Use a service. You can't pass data to routes, other than simple values.

    export class FirstComponent {
       constructor(private someService: SomeService){}
    
       someMethod(item) {
         this.someService.currentItem = item;
       }
    }
    
    export class SomeService {
      currentItem: any;
    }
    
    export class SecondComponent {
       constructor(private someService: SomeService){}
    
       someMethod() {
        // now you have the item
        this.currentItem.....
        }
    }
    

    Instead of routerLinking to a route, use the method to redirect and add the item to the service:

    so instead of

    <a routerLink
    

    do:

    *ngFor="let item of items"
    <button (click)="route(item)"
    
    myMethod(item) {
      this.someService.currentItem = item;
      this.router.navigate('/route....')
    }
    

    syntax is not exact; it's just an example