Often, we face the problem of data sharing in Angular. Data sharing when the component are in Parent-Child or Child-Parent can be done using input , output, ViewChild & EventEmitter. But when it comes to two component which has no relation between each other.The common technique we use is creating a shared Service.

Framework such as React uses state to share data between unrelated components. Angular 7.2 now support this technique to share data. We will using the same technique to share data which reduces a lot of codes. Mainly, reducing our development time.

Share data using RouterLink or Router

<a routerLink="/" [state]="{ data: 'value' }">Click here</a>

this.router.navigate(['/'], { state: { data: 'value' } });

Note: the state must be an object.

Retrieve the state data

After the data is passed, to retrieve the data , we call the getCurrentNavigation function from router instance.

this.state = this.router.events.pipe( filter(e => e instanceof NavigationStart), map(() => this.router.getCurrentNavigation().extras.state) )

In the above code, we retrieved the state data using router event thus, reducing shared Service code & less code obviously :)

We can see how easily we retrieved the data using state. Routerlink passes a parameter state which can be catch using router instance.