Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - send object from one component to another over router-link

Im trying to send an object over router-link in angular 2. I create a person-profile component for every person object in my person array people and display them on my screen.

<div *ngFor="#person of people; #i = index">
    <person-profile  [person]="person"></person-profile>
</div>

The person-profile component displays several pieces of information contained in the person object. Im trying to send the entire person object from the person-profile component to a component named "map" using a router-link and passing the person object as a parameter.

<person-profile>
  ..code..
    <tr>
       <td class="category">Address</td>
       <td>{{ person.visiting_address }}</td>
       <td *ngIf="person.visiting_address"><a [routerLink]="['Map',{person:person}]">View on map</a></td>
    </tr>
..code..
<person-profile>

In my map component i retrieve the object with:

var person = <any> routeParams.get('person');

The problem is that i get the same person every time in the map component regardless of which <person-profile> i execute the router-link from. Its always the first person in the people list. The weird thing is that if i pass specific parameters from the person object it works. For instance, if i pass person.family_name instead of the the entire person object everything works but i want to send the entire object. Any suggestions?

Thanks!

like image 854
Jakob Svenningsson Avatar asked Apr 14 '16 09:04

Jakob Svenningsson


People also ask

How do you send an object from one component to another component?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.

How do I pass data from one component to another in JSON?

Passing Values Using Props React components can access data from other components via props. Props are used to send data from one component to another. In the below example, the Hello component accepts a name prop. Similarly, JSON values can be passed inside the props.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.


1 Answers

AFAIK there is no way to pass objects because the source of the RouterLink class doesn't indicate any support for that and because the data needs to be presented in the URL string.

My suggestion is to pass an ID and share the users in a service that allows to fetch the concrete instance by ID.

like image 135
Günter Zöchbauer Avatar answered Oct 04 '22 01:10

Günter Zöchbauer