简体   繁体   中英

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. Eg /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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM