angularangular10

How to pass data between routed components in Angular


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 ?


Solution

  • 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(['route_to_comp_b/' + `${params_if_any}`], {
        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