Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router: How to share a value from parent to child routes?

In an Angular2 app (using the final 1.x release) I have a page with several tabs. The parent state /samples/{id} has a child route for each tab. E.g. /samples/{id}/location or /samples/{id}/execution.

The sample data is one big object that is sent in one request by the server API, containing the data for all the tabs. So I want to load it only once, when the parent route is activated (in the component code or maybe in a resolve), then read from it in all my tabs.

Is there a way to directly share an object from the parent component to the components of the children routes ? Sort of like the scope was inherited in Angular 1 ?

I know I can use a service to share the object, I am just curious if there is a built-in solution.

I also know it is possible to get route parameters from the parent route but it would not be very useful in that case.

like image 254
Pierre Henry Avatar asked Nov 29 '25 05:11

Pierre Henry


1 Answers

The "built-in solution" actually is using a shared service.

There is also the option of using @Input() decorators, but in your case it is not applicable, since you are using routes as far as I can tell. That is only applicable in parent-child relationships, where the child is inside the parent component.

Another option would be using a Route Data Resolver which resolves data before activating a route, but since the data is already loaded, the shared service option is the most optimal solution for your case.

like image 104
Alexander Ciesielski Avatar answered Nov 30 '25 18:11

Alexander Ciesielski