send data to another component through route in angular

7.8k Views Asked by At

I am working on an angular application and realized that in the latest versions of angular, data can be transferred one component to other through routes. I have gone through some blogs but I am not very clear of how to do that.

My code

component1.ts

sendMessageto2() {
    par = this.param
    this.router.navigate(['/vav'],{state : {data : {par}}})
    console.log(this.param)
  }

I want to pass a variable this.param to component2

component1.html

<area shape="rect" coords="818,232,917,262" (click)="sendMessageto2()">

component2.ts

ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
    .pipe(map(() => window.history.state))  
  }

I am not sure how to get this data in the component2 .I get an error for map. Could not find map.Can some one help me with this?

Thanks

4

There are 4 best solutions below

4
On BEST ANSWER

For passing data you can do this

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

For receiving on other page

constructor(public router: Router, public route: ActivatedRoute){}
route.params.subscribe(params => {
        let data = params['data']
    });
0
On

Try this

On component 2

ngOnInit() {
    this.state$ = this.route.snapshot.paramMap.get('param') ; 
  }

'param' value is the value that has been added to the url from component 1 .

0
On

You can pass like this:

routing.ts

{path: 'component2', component: YourComponent2} // configure it in the routing file

component1.ts

private router: Router // import router
this.router.navigate(['/component2', {id: '1', name: 'surjeet'}]);

component2.ts

private route: ActivatedRoute // import ActivatedRoute
this.route.snapshot.paramMap.get('id');
this.route.snapshot.paramMap.get('name');
3
On

I assume the data you are trying to pass is a string. Define your route like this,

const routes: Routes = [
  { path:'', component : C1Component },
  { path:'vav', component : C2Component },
];

When routing, add the value in URL as queryParams,

let navigationExtras: NavigationExtras = {
    queryParams: {
        "data"   : encodeURIComponent('Your data'),
    }
};

this.router.navigate(["vav"], navigationExtras);

Fetch the queryParams in second component using ActivateRoute,

decodeURIComponent(this.route.snapshot.queryParams['data']);

Demo : https://stackblitz.com/edit/angular-5zw742

If the data is an object, JSON.stringify() it before encoding and JSON.parse() it after decoding.