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.

1

2 Answers 2

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'])
  })
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah but this way I'm getting an id and not the whole object
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.
Hm, I found this solution stackoverflow.com/a/39569933/5206428 which works but stops working if I refresh route on /animal/:id
SessionStorage and LocalStorage won’t have such issue
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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.