1

From a Angular component I am navigating to a different component also by passing some arguments.

What I want to do is to retrieve the ani object that I passed from the animalComponent part of it, So I could use the passed object within that component.

Can someone help me out with this ?

displayAnimals(ani) {
    this.router.navigate(['/ani/animalComponent', {text1 : ani}]);
  }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Illep
  • 16,375
  • 46
  • 171
  • 302
  • Possible duplicate of [How do I pass data to Angular routed components?](https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components) – Jota.Toledo Jun 03 '18 at 07:22
  • pass data in queryparam while navigating and in target component use `ActivatedRouter` for getting data. – Ravi Sevta Jun 03 '18 at 07:39

2 Answers2

0

You can do on the component as,

Console.log(this.route.snapshot.paramMap.get('text1'));

also you can use service to pass data from one component to another without using route parameters at all. Here is a good blog on the same

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Better you pass data in queryparam,

step 1 : pass data in navigation

this.router.navigate(['/ani/animalComponent'], {queryParams: {text1 : ani}});

step 2 : and get in another component

constructor(private activateRoute: ActivatedRoute) {
    const txt = this.activateRoute.snapshot.queryParams['text1'];
}

Or

Use service

provide a service in module level and inject it to both components to put and get data.

Keep in mind that scope of that service should be greater then both component so that is can be available in components.

for detail information, go through this link

Ravi Sevta
  • 2,817
  • 21
  • 37
  • Since I am passing an object here, Is there is a better way to pass it. Actually, in the approach I am trying ,the object gets displayed in the URL. How can I send it via the body as in not displaying it in the URL. – Illep Jun 03 '18 at 08:04
  • for that you should use services, set data in first component and get data in another component, and also scope of that service must be greater than both component so that its instance is available is both components. – Ravi Sevta Jun 03 '18 at 09:13