Angular: Passing Data Between Unrelated Components
Let’s explore how we can pass data between unrelated components, i.e., components that don’t have a parent/child relationship.
Using shared services
Passing data between unrelated components can be done through shared services. The following is a service that contains some data:
This service simply contains a private property called message
, which can be changed by calling the changeMessage()
function and retrieved using the getMessage()
function.
The important part of this service is the @Injectable
decorator. This tells Angular that this class can be injected into other classes, both components, and services.
First component
This is an example of a component using this service:
Here, we are injecting DataService
using the constructor of the component class, then calling the DataService’s getMessage()
function to set the component’s message
property to the value in DataService
.
Second component
Here is another example of the component using this service:
In this unrelated component, we are also injecting DataService
, but when the user clicks the button from the template, the changeMessage()
function of DataService
is called, passing on a new message.
This will then update the message
property in DataService
, changing the value that is available to our original parent component. The reason that this data is the same for both components is that the service in Angular is using a singleton design pattern. This means that both components are accessing the same data from the same class.
Using a service means that you can load data from an external source and share that data between components. When we look at services in more detail later, we will see how to load data from external sources and how services are designed. We will also go in more detail of the singleton design pattern, explaining how data is shared by the service.