简体   繁体   中英

Angular - resolver and component not sharing injected service?

I have a table to display some products in my products list component. There is a moderate amount of data, so I've added in a resolver to not land the user on the page until the data is loaded. Right now, my resolver injects my products service, which has its own methods to load the data from my backend and save the products in an array inside the service. So my resolver injects this service, calls the load products function to prefetch the data and then the component loads.

The question is now, what's the best way to re-use the data in the products list component? For some reason, if I inject the same service into the products list component, I can see that the products are not loaded, so I'm not sure if my resolver and component are injecting the same singleton of my service.

If I simply use the resolver to pass along the products that it got from the service itself, then my component can get access to these, but when it comes to making updates to them, it won't be writing changes to my products list service, which is needed elsewhere for other components.

What's the best structure/approach to this kind of setup. I'm sure it can't be that uncommon?

If you look at Angular documentation there is stated as follows "Do not specify app-wide singleton providers in a shared module . A lazy-loaded NgModule that imports that shared module makes its own copy of the service.."

So an service you want to have as an singleton should be provided in the Core module which you import once when the app starts and never import anywhere else.

Here is the link to the detailed explanation of the Core module.

Have a great day :)

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