How to pass data between routed components in Angular

Viewed 1497

I have a routed component like this:

enter image description here

From component A: I have an object that was fetched through an API, At the moment I have a button that is redirecting me to Component B.

There is no parent child relationship between components A and B.

What I want to do is to send that object while redirecting to component B, So I can work on it.

I don't want to pass the data through the URL like this:

 return this.router.navigate(['associate-product/' + this.id, {this.data}]);

Also I don't want to store the object on LocalStorage.

Is there a way to achieve this ?

3 Answers

Using Routing

If you want to pass data from one component to another using routing, you can use NavigationExtras.

In CompA you can do:

constructor(private router: Router){
}

goToCompB(){
  this.router.navigate(['associate-product/' + this.id], {
    state:{
      data: yourDataToShareWithCompB
    }
  });
}

In CompB you can do:

constructor(private router: Router){
 const data = router.getCurrentNavigation().extras.state.data;
}

PS: You can also use service based pattern as answered by others

you can use a service with Subject/ Behavior in order to achieve that, like described in their docs

Using service, you can share data through your components that injects the service.

I have created a stackblitz with a little example of possibility to share the data and to know when the data is retrieved from API.

On this example, you have 2 components, A and B, and a service, "example".

On your first component (A) you call the API to get data, on the example I've made a seTimeout to simulate an asynchronous call.

Then, when the call is finished, a button to move to b can be shown, and on component b there is the data that was retrieved from the timeout.

Related