Maybe the question is too broad, so I can not give you a precise solution, but let's try to clarify ideas. If you have two components in an application that have to share data, the ways to do it vary depending on the relationship between these components:
If one component is the parent of the other
-
The parent component passes information to the child when declaring its use in the template:
In the father you will have some declared attribute (let's call it datos
):
<app-componente-hijo [entrada]="datos"> </app-componente-hijo>
And in the child you will have an input:
@Input() entrada;
-
The son sends information to the father:
<app-componente-hijo (onDataReceived)="leerDatos($event)"> </app-componente-hijo>
Here the child declares with @Output()
an issuer ( EventEmitter
) to which the parent subscribes by passing the function that will treat the data.
If the components have a common father
This case is similar to the previous ones: the parent component can receive / send data from one child to another through input / output
If the components have no relationship beyond being in the same instance of the application
In this case, the usual thing is to use a service: one component uses this service to send the data and the other component uses it to receive it (the communication can be bidirectional).
The service can keep the data in memory (a variable acts as a temporary buffer) or can save them in a more persistent place (localStorage in the browser or could even send the data to the server).
If the components are in different instances of the application
This is the equivalent of having two open desktop applications and trying to communicate two objects of each application: you need something external to the applications, such as the server or the localStorage (if you have a service class of type LocalStorageService
, you'll have two instances, but they share the browser's memory)