There are plenty of examples showing us how to pass data between parent and a child component.  This one on for example.

This post is an example on how to pass data between two separate components using a service.

Here is what we want to achieve:

  • the sender component creates or retrieves the data from a database
  • sets the data as a property of the data service
  • sender component calls receiver component
  • receiver component uses the data service to retrieve the data set by the sender component

Let’s make a service that is able to hold the data you want to pass between the components first.

We are going to be using the sender component to set the data, so let’s create that.

Now for the receiver component.

This however, this came with an expected side effect.  If the user refreshed the browser, the service no longer held the value.  Not sure how to overcome this at the moment without using local storage.

To store an object in the session storage:

sessionStorage.setItem('key', JSON.stringify(object));

to retrieve it back as an object: