I have a component in Angular2 hosting the table of users (userTableComponnent) and another component of userDetails. Upon clicking on a row in users table, I want to route to the userDetails. One implementation is to pass the userId only, so in userDetails, I fetch the details of the user with another http get. However, this is redundant, as I grab all the user info in userTableComponent. So what I really need is to pass the User object from userTableComponent to userDetails. Any idea how to achieve it through routing?
Asked
Active
Viewed 5.6k times
2 Answers
18
You can create a SessionService class and pass it around your App via Dependency Injection.
Once the user is selected you can attach the relative data to the SessionService instance injected via DI and retrieve it in the userDetails Component.
I hope it helps

Picci
- 16,775
- 13
- 70
- 113
-
Thanks for the reply. It looks great – Hammer May 03 '16 at 05:13
-
Don't you think the shared service may lose its data when the page is refreshed by the user? – Salman Kazmi Nov 16 '17 at 06:25
-
2If refresh means using F5 key, yes, everything is lost since you are reloading the app, unless you use local storage. Consider that these are Single Page Applications, which means, among other things, that they start fresh the moment they are loaded onto the browser. – Picci Nov 16 '17 at 14:10
-
You can survive an F5 refresh by using an data service that uses the APP_INITIALIZER token, e.g. I use such service to load "global" data for the app, so most pages can survive a reload. However, if you have a page that has data passed behind-the-scenes then you risk allowing F5 to "break" your apps resiliency. Besides loading data in the APP_INITIALIZER, you can use resolvers, or in the URL you can pass an ID as a query param and have a given page load the necessary data by ID in onInit method, for example. – sarora Dec 12 '17 at 02:05
-
https://stackoverflow.com/a/36835156/185123 see update here – spottedmahn May 20 '18 at 16:34
8
Passing objects by routing is quite limited. Using a service is the better option. If you provide a service instance by the parent component, then the same instance gets injected in parent and child and you have the shared data available immediately.
See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
In RC.4 also data
for routes was re-introduced How do I pass data in Angular 2 components while using Routing?

Community
- 1
- 1

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567