2

I have a component which looks like this

<div class="animal">
  <a routerLink="/animal/{{animal.id}}">
  <div>
    ...
  </div>
  </a>
</div>

It gets animal object from parent component, which is just a list of childs.

@Input() animal;

When I click on it I'm moving to another component where I want to display some propreties from this clicked animal object.

I thought of create a service which will store this object but the problem is I don't know how to get only clicked object and not every object from the list.

All the help will be much appreciated.

Siavash
  • 2,813
  • 4
  • 29
  • 42
Person
  • 2,190
  • 7
  • 30
  • 58
  • 1
    there are two ways to pass value, ```path variables``` and ```query params``` check this answer: https://stackoverflow.com/a/48125257/4294381 – Saad Mehmood Oct 31 '18 at 11:43

2 Answers2

2

You can catch your parameters in your routed Component by using ActivatedRoute in angular

Your routing path :

const routes : Routes = [
  { 
    // Other routes
  },
  {
     path:'animal/:id'
     component : AnimalDetailsComponent
  }
]

animal-details.component.ts

constructor(private route : ActivatedRoute) {} 

ngOnInit(){
  this.route.params.subscribe((params)=>{
     console.log(params['id'])
  })
}
Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12
  • 2
    Yeah but this way I'm getting an id and not the whole object – Person Oct 31 '18 at 12:57
  • if you want to send whole object, you can either use `EventEmitter` or `Subject` or `BehaviorSubject` with the help of `service`. You can also make use of `SessionStorage` or `localStorage` for communication between components. – Sarthak Aggarwal Oct 31 '18 at 13:00
  • Hm, I found this solution https://stackoverflow.com/a/39569933/5206428 which works but stops working if I refresh route on `/animal/:id` – Person Oct 31 '18 at 13:18
  • SessionStorage and LocalStorage won’t have such issue – Sarthak Aggarwal Oct 31 '18 at 13:22
0

Try using resolver Route Resolver Service - where you can do some action before the routing loads

 {
    path: '',
    component: Component,
    resolve: { service: Service },
  },

export class Service implements Resolve<object | string> {

  constructor() {
    }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<object | string> | Promise<object | string>  {
        return {};
    }

In your onInit you can read the data by injecting a ActivatedRoute service in your component constructor like this

constructor(private _activatedRoute: ActivatedRoute) {
    }

Code in Onint - this.variable = this._activatedRoute.snapshot.data["service"];

Rahul
  • 2,040
  • 2
  • 11
  • 29